0

Pretty new to React, and I'm sure this is easy, but I'm trying to convert this:

    return values.map(value => {
        if(head) return <th key={uuidv4()}> {value} </th>;
        return <td key={uuidv4()}> {value} </td>
    });

into a single return statement.

Basically a conditional check that replaces the <th> tags with a <td>. In vanilla I'd just return a template string, but I can't seem to get this to work with jsx. (Something like this) <${head? 'th': 'td'} key=${uuidv4()}>${value}</${head? 'th': 'td'}>

I feel like I'm close, but I'm obviously returning a string ::shrug::

Any help appreciated,

Thanks

NickW
  • 1,207
  • 1
  • 12
  • 52
  • Yes it does, thanks - I did try to search but didn't think to call it a dynamic tag. Strange that it's not possible – NickW Feb 06 '21 at 18:03

2 Answers2

1

I would do

return values.map(value => {
    return head ? <th key={uuidv4()}> {value} </th> :
                  <td key={uuidv4()}> {value} </td>
});

It is important to say: The "duplication" of code in the 2 options (td or th) is in my opinion great! because these are two different types of UI features you have. It is better to keep them separated and keep it possible to put changes in each one of them alone.

Ravid
  • 293
  • 2
  • 9
  • yeah, I guess it's just bugging me that I can' seem to work out how to replace parts of the statement, but thanks :) – NickW Feb 06 '21 at 17:58
  • You're welcome, please notice the edit for the answer about the code structure. – Ravid Feb 06 '21 at 18:00
1

Try this :

return values.map(value => {
  const Tag = `h${head ? 'th' : 'td'}`;
  return <Tag key={uuidv4()}>{value}</Tag>
});
Jérémie B
  • 10,611
  • 1
  • 26
  • 43
  • Thanks! Definitely like this approach, even though it's not a single line – NickW Feb 06 '21 at 18:07
  • Out of interest - I changed the flag to a string and tried to put it directly as the tag itself, ie: `{value}` - but it only works when assigned with a captial letter as you've done. Not quite sure why? – NickW Feb 06 '21 at 18:20
  • It's a convention for React : Uppercase = function/component, otherwise it's an html element. – Jérémie B Feb 06 '21 at 18:50