How can I convert an array of string shown below
var players = ['ronaldo','messi','naymar','suarez','ozil']
into a jsx statement as shown below
<b>ronaldo</b> and <b>messi</b> and <b>naymar</b> and <b>suarez</b> and <b>ozil</b> and <b></b>
I tried to use .map
and .join
as shown below
players.map(player => <b>player</b>).join('and');
But it rendered out like this
[object Object] and [object Object] and [object Object] and [object Object]......
How can I achieve this? Thanks in advance
join
joins all elements of an array into a string, so it will be hard to use that with JSX, since JSX is just a bunch of React.createElement
calls under the hood.
You could use React.Fragment instead and add and
for all entries in the array except the last.
players.map((p, index) => (
<Fragment>
<b> {p} </b> {players.length - 1 !== index && "and"}
</Fragment>
));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With