Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert array into array of React components separated by string

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

like image 632
Johnson Cherian Avatar asked Mar 05 '23 21:03

Johnson Cherian


1 Answers

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>
));
like image 157
Tholle Avatar answered Apr 06 '23 05:04

Tholle