Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why doesn't this.props.children.map work?

Tags:

I have written this code in several other components but can't seem to understand why this isn't working.

{     this.props.children.map(function(child) {         return <li>{child}</li>     }) } 

Any help would be greatly appreciated!

like image 282
epicsharp Avatar asked Apr 06 '15 02:04

epicsharp


People also ask

Why use React children Map props children?

React. Children. map is a utility function to help you handle different cases. Invokes a function on every immediate child contained within children with this set to thisArg.

What is the children prop and why is it useful?

The React children prop is an important concept for creating reusable components because it allows components to be constructed together. However, a common issue with using React with Typescript is figuring out which data type to use with React children since Typescript is a strongly typed library.

What is a React child?

What are children? The children, in React, refer to the generic box whose contents are unknown until they're passed from the parent component. What does this mean? It simply means that the component will display whatever is included in between the opening and closing tags while invoking the component.


1 Answers

this.props.children is an opaque data structure. It can be either an array or a single element. In your case, this.props.children is probably a single element, which is why the .map() method is undefined.

You should use the React.Children API when manipulating the children prop.

See also Type of the Children props.


enter image description here

like image 71
Alexandre Kirszenberg Avatar answered Sep 28 '22 09:09

Alexandre Kirszenberg