Concatenate JSX elements into an Array in React

avatar

Borislav Hadzhiev

Last updated: Apr 29, 2022

banner

Check out my new book

Concatenate JSX elements into an Array in React #

To concatenate JSX elements into an array in React:

  1. Initialize an empty array.
  2. Use the push() method to push JSX elements into the array.
  3. Set the key prop on the outermost JSX element to a unique value.
App.js
export default function App() { const fruits = []; fruits.push(<div key="apple">Apple</div>); fruits.push(<div key="banana">Banana</div>); fruits.push(<div key="kiwi">Kiwi</div>); // 👇️ or if you have an array of strings const names = ['Alice', 'Bob', 'Carl']; const namesJsx = []; names.forEach((name, index) => { namesJsx.push( <div key={index}> <h2>{name}</h2> <hr /> </div>, ); }); return ( <div> <div>{fruits}</div> <br /> <div>{namesJsx}</div> </div> ); }

The first example pushes JSX elements into an array and then renders the array of elements.

We had to set the key prop on each element to a unique value.

App.js
const fruits = []; fruits.push(<div key="apple">Apple</div>); fruits.push(<div key="banana">Banana</div>); fruits.push(<div key="kiwi">Kiwi</div>);

The key prop is used internally by React for performance reasons. It helps the library make sure to only re-render the array elements that have changed.

The second example shows how to iterate over an array of strings using the forEach() method and push a JSX element into a new array on each iteration.

App.js
const names = ['Alice', 'Bob', 'Carl']; const namesJsx = []; names.forEach((name, index) => { namesJsx.push( <div key={index}> <h2>{name}</h2> <hr /> </div>, ); });

The Array.forEach method can be used when you need to call a function for every element in an array.

However, forEach() can't be used to iterate over an array directly in your JSX code.

The forEach() method calls the provided function with each element in the array but returns undefined.

Using it directly in our JSX code wouldn't make sense because we need to return JSX elements and not undefined.

You can use the forEach() method to:

  1. Iterate over an array.
  2. Push JSX elements into a new array.
  3. Render the JSX elements.
App.js
export default function App() { const names = ['Alice', 'Bob', 'Carl']; const namesJsx = []; names.forEach((name, index) => { namesJsx.push( <div key={index}> <h2>{name}</h2> <hr /> </div>, ); }); return ( <div> <div>{namesJsx}</div> </div> ); }
Use the search field on my Home Page to filter through my more than 3,000 articles.