How to render react components by using map and join?

Posted by Prem Tiwari | Updated on

If you want to render react components by using map and join A simple solution is to use reduce() without second argument and without spreading the previous result:

Without second argument, reduce() will start at index 1 instead of 0, and React is perfectly happy with nested arrays.

As said in the comments, you want to only use this for arrays with at least one item, because reduce() without second argument will throw with an empty array. Normally this should not be a problem, since you want to display a custom message saying something like ‘this is empty’ for empty arrays anyway.

Update for Typescript

You can use this in Typescript (without type-unsafe any) with a React.ReactNode type parameter on .map():

If you like this question & answer and want to contribute, then write your question & answer and email to freewebmentor[@] Your question and answer will appear on and help other developers.

Related Questions & Answers