tinydancer
tinydancer

Reputation: 15

How do you join an array of strings and HTML elements in React?

I have a list of names that I need to return with commas in between, so normally I'd just use .join, but one item in the list will need to have the icon of a star next to it based on if a condition is met, which doesn't work in the join. Is there something similar to a join that I could use that doesn't turn everything into a string so that it displays the HTML element instead of returning 'name, [Object, object]'? I tried using dangerouslySetInnerHTML, but it continues to just say name, [Object, object] instead of name, <Icon name='star' />name2 with an actual star displaying, not the text for the component.

Upvotes: 1

Views: 1312

Answers (1)

Michael Lyons
Michael Lyons

Reputation: 584

So if Icon is another React element, you should wrap each name is a <span> element so that as you loop through the array, you can add the Icon as a sibling to the correct string content.

It could look like this:

names.map((name, i) => {
   return <span key={i}>
           { 
            name === focusName ? // However you determine where the star goes
            <Icon name="star" /> :
            null
           }
           { // Add a comma to name if not last item
             name + (i < names.length - 1 ? ',' : '')
           } 
          <span>
});

Upvotes: 1

Related Questions