Can I use .forEach() to create a list of JSX elements?

Question

Can I use .forEach() to create a list of JSX elements?

Answer

We can use .forEach() to create a list of JSX elements from an array as long as we are using .forEach() from outside a JSX expression as .forEach() does not evaluate to a value like .map() does. That said, .forEach() takes a little more code to do the same thing that .map() can do.

For example:
Using .forEach():

const myArr = ['one', 'two', 'three'];

const myArrMadeFromForEach = []; // we create a new array which will evaluate to a value when we inject it into a JSX expression

myArr.forEach((item, i) => myArrMadeFromForEach.push(<li key={item+i}>{item}</li>)); // we push a JSX element containing a value to our 'myArrMadeFromForEach' because `.forEach()` does not return any value, nor does it mutate the array on which it is called

const myList = (
  <ul>{myArrMadeFromForEach}</ul> // `myArrMadeFromForEach` will evaluate to an array of `<li>` elements
)

ReactDOM.render(myList, document.getElementById('app'));

compared to using .map():

import React from 'react';
import ReactDOM from 'react-dom';

const myArr = ['one', 'two', 'three'];

const myArrCreatedFromMap = myArr.map((item, i) => (<li key={item + i}>{item}</li>)); // `.map()` creates/returns a new array from calling a function on every element in the array it's called on

const myList = (
  <ul>{myArrCreatedFromMap}</ul> // `myArrCreatedFromMap` will evaluate to a list of `<li>` elements
)

ReactDOM.render(myList, document.getElementById('app'));

we can also use .map() inline without setting the return value to a variable:

import React from 'react';
import ReactDOM from 'react-dom';

const myArr = ['one', 'two', 'three'];

const myList = (
  <ul>{myArr.map((item, i) => <li key={item + i}>{item}</li>)}</ul> // `.map()` creates/returns a new array from calling a function on every element in the array it's called on
)

ReactDOM.render(myList, document.getElementById('app'));
8 Likes

Imperative VS Declarative

3 Likes

But what if I want to use an array that I have from my elements props?
So let’s say for such React functional element:

<Text text={["a", "b", "c"]}/>

I wanna do something like this:

  function Text(props)
  {
    return(
        <center>
            {props.text}.map(paragraph =><p>paragraph</p>)
        </center>
    )
  }

This was what I tried, but that obviously didn’t work. So I wonder how to make it work to get results from this element as this HTML Code:

 <center>
            <p>a</p>
            <p>b</p>
            <p>c</p>
</center>
1 Like

You are so close to working code. Just needed to move a curly-brace and add another set.

function Text(props) {
  return (
    <center>
      {props.texts.map((paragraph, i) => (
        <p key={i}>{paragraph}</p>
      ))}
    </center>
  )
}
4 Likes

I am getting an error on browser console even I define the “key” as given a solution. Any idea how to clear this error ? Thank you

Warning: Each child in a list should have a unique “key” prop.

You haven’t shared your code ([How to] Format code in posts) so it is difficult to see how exactly you are trying to provide the keys.

As for the error, have a look at:
https://react.dev/learn/rendering-lists#keeping-list-items-in-order-with-key
(from the section titled “Keeping list items in order with key” to the end of the article)

It is a short but useful read. Make sure to also read the pitfall about why using the index as a key can be problematic.

thank you very much. I saw it on next chapter.