Home > OS >  using forEch to render react components
using forEch to render react components

Time:10-11

I'm trying to use forEach to render my components.

{myArray.forEach((value, index) => {
    <MyComponent {...value} />
})}

this is not doing anything. but if I do

{myArray.forEach((value, index) => {
    console.log(index, value)
})}

//also tried with...

{myArray.forEach((index) => {
    <MyComponent {...myArray[index]} />;
})}

I see the element in the console. why is that? I read that forEach returns undefined and I should use map to iterate but why it shows the object in the console but doesn't render my component? thank you

CodePudding user response:

Foreach doesn't return anything. But for rendering any component inside the jsx you have to return an array of JSX.Elements or HTMLElements. Try using map instead of forEach.

{array.map((value, index) => {
    return <MyComponent {...value} />
})}

CodePudding user response:

first thing forEach function does not return a value but rather only executing the code that is inside of it, therefor you see the console.logs.

In React it is best practice to use the map function.

So instead of doing this

{array.forEach((value, index) => {
    <MyComponent {...value} />
})}

Do this

{array.map((value, index) => {
    return <MyComponent {...value} />
})}
  • Related