19

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

}

1 Answer 1

62

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.

Sign up to request clarification or add additional context in comments.

1 Comment

I am using map but still face the same issue. The element is of type never even though it has values.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.