I have a small application when you open a tab the React Route redirects to the given component (container). And from the container i want to render the child components. I use the foreach loop to go through a list that has the props that need to be given to the child. However, the child doesn't get rendered.
I don't want to use map because i use libraries that depend on the list class.
render() {
return (
<div>
{this.state.list.ForEach((element) =>
<ChildComponent childName={element.name}
}
</div>
);
}
}
You are confusing Array.forEach with Array.map. forEach
does not return anything. The correct way is:
<div>
{this.state.list.map((element, index) =>
<ChildComponent key={index} childName={element.name} />
)}
</div>
map
converts the given element
into another element, a component in this case. The result of calling map
is an array of components that is then rendered. forEach
always returns undefined
therefore the result of your code is the same as writing:
<div>
{undefined}
</div>
Note that key
is also necessary when rendering lists of components.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With