Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React - component will not render in foreach loop?

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> 
    );
}

}

like image 526
Skatedude Avatar asked Oct 15 '17 08:10

Skatedude


1 Answers

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.

like image 90
Sulthan Avatar answered Sep 23 '22 12:09

Sulthan