react how to pass props to child code example
Example 1: react pass props to children
import React, { Children, isValidElement, cloneElement } from 'react';
const Child = ({ doSomething, value }) => (
<div onClick={() => doSomething(value)}>Click Me</div>
);
function Parent({ children }) {
function doSomething(value) {
console.log('doSomething called by child with value:', value);
}
render() {
const childrenWithProps = Children.map(children, child => {
if (isValidElement(child)) {
return cloneElement(child, { doSomething })
}
return child;
});
return <div>{childrenWithProps}</div>
}
};
ReactDOM.render(
<Parent>
<Child value="1" />
<Child value="2" />
</Parent>,
document.getElementById('container')
);
Example 2: how to pass props from child to parent
class ToDoList extends React.Component { constructor(props) { super(props); this.state = { listDataFromChild: null }; }, myCallback = (dataFromChild) => { this.setState({ listDataFromChild: dataFromChild }); }, otherFn = () => { [...within this other function now I still have access to this.state.listDataFromChild...] } render() { return ( <div> <ToDoItem callbackFromParent={this.myCallback}/> [...now here I can pass this.state.listDataFromChild as a prop to any other child component...] </div> ); }});