Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to iterate through a Component's Children in Typescript React?

Tags:

How do I iterate through a React component's children in Typescript tsx?

The following would be valid jsx:

public render() {     return (         <div>             {React.Children.map(this.props.children, x => x.props.foo)}         </div>     ); } 

However, in Typescript, the type of x is React.ReactElement<any> so I have no access to props. Is there some kind of casting that I need to do?

like image 393
CookieOfFortune Avatar asked Dec 01 '15 21:12

CookieOfFortune


People also ask

How do I get Onclick to child React?

To pass an onChange event handler to a child component in React: Define the event handler function in the parent component. Pass it as a prop to the child component, e.g. <Child handleChange={handleChange} /> . Set it to the onChange prop on the input field in the child.

Can you iterate through an object React?

Use the Object. keys() method to get an array of the object's keys. Use the map() method to iterate over the array of keys.


1 Answers

Using any should generally be avoided as you're losing the type info.

Instead use React.ReactElement<P> in the function parameter type:

React.Children.map(this.props.children, (child: React.ReactElement<ChildPropTypes>) => child.props.bar) 
like image 54
Ian Chadwick Avatar answered Oct 15 '22 13:10

Ian Chadwick