is there a way to do array.join in react is there a way to do array.join in react reactjs reactjs

is there a way to do array.join in react


You can also use reduce to insert the separator between every element of the array:

render() {  let myArray = [1,2,3];  return (    <div>      {        myArray          .map(item => <div>{item}</div>)          .reduce((acc, x) => acc === null ? [x] : [acc, ' | ', x], null)      }    </div>  );}

or using fragments:

render() {  let myArray = [1,2,3];  return (    <div>      {        myArray          .map(item => <div>{item}</div>)          .reduce((acc, x) => acc === null ? x : <>{acc} | {x}</>, null)      }    </div>  );}


Trying to .join with React Elements is probably not going out pan out for you. This would produce the result you describe needing.

render() {    let myArray = [1,2,3];    return (      <div>        {myArray.map((item, i, arr) => {          let divider = i<arr.length-1 && <div>|</div>;          return (            <span key={i}>                <div>{item}</div>                {divider}            </span>          )        })}      </div>    );  }


You can also do it by combining .reduce and React fragments.

function jsxJoin (array, str) {  return array.length > 0    ? array.reduce((result, item) => <>{result}{str}{item}</>)    : null;}