My structure looks as follows:
Component 1
- |- Component 2
- - |- Component 4
- - - |- Component 5
Component 3
Component 3 s
so, if you want to update parent component,
class ParentComponent extends React.Component {
constructor(props){
super(props);
this.state = {
page:0
}
}
handler(val){
console.log(val) // 1
}
render(){
return (
)
}
}
class ChildComponent extends React.Component {
constructor(props) {
super(props);
this.state = {
page:1
};
}
someMethod = (page) => {
this.setState({ page: page });
this.props.onChange(page)
}
render() {
return (
)
}
}
Here onChange is an attribute with "handler" method bound to it's instance. we passed the method handler to the Child class component, to receive via onChange property in its props argument.
The attribute onChange will be set in a props object like this:
props ={
onChange : this.handler
}
and passed to the child component
So the Child component can access the value of name in the props object like this props.onChange
Its done through the use of render props.
Now the Child component has a button “Click” with an onclick event set to call the handler method passed to it via onChnge in its props argument object. So now this.props.onChange in Child holds the output method in the Parent class Reference and credits: Bits and Pieces