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?
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.
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.
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)
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