I'm getting a Syntax error on the "if" statement in the code below. Am I crazy? I know its long, but it still returns a single root element, right?
<tbody>
{items.map((item, index) => (
<tr key={index}>
{if (tileView) {
switch (header) {
case "Items":
(item.product.pictures[0]
? <td><img src={item.product.pictures[0].url} alt={item.name}/></td>
: <td><Items/></td>)
break;
case "Accessories":
(item.accessory.pictures[0]
? <td><img src={item.accessory.pictures[0].url} alt={item.name}/></td>
: <td><Items/></td>)
break;
case "Add Ons":
(item.add_on.pictures[0]
? <td><img src={item.add_on.pictures[0].url} alt={item.name}/></td>
: <td><Items/></td>)
break;
default:
break;
}}}
<td>{item.name}</td>
<td>{item.quantity}</td>
<td>
<FormattedNumber
value={item.selectedPrice ? item.selectedPrice : 0}
style="currency"
currency="USD"
/>
</td>
</tr>
))}
</tbody>
If I remove the default on the switch/case, I get the same thing. To be fair, this is probably my first time doing switch statements in React.
EDIT: ANSWER: Here's the final code. I created an object to index the right attribute: const HeaderToAttribute = { "Items": "product", "Accessories": "accessory", "Add Ons": "add_on" }
<tbody>
{items.map((item, index) => (
<tr key={index}>
{ tileView &&
(item[HeaderToAttribute[header]].pictures[0]
? <td><img src={item[HeaderToAttribute[header]].pictures[0].url} alt={item.name}/></td>
: <td><Items/></td>)
}
<td>{item.name}</td>
<td>{item.quantity}</td>
<td>
<FormattedNumber
value={item.selectedPrice ? item.selectedPrice : 0}
style="currency"
currency="USD"
/>
</td>
</tr>
))}
</tbody>
return. In a switch-case the last statement is abreak, therefore you are not returning anything. You will have to replace(...); break;with an explicitreturn (...).