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 (
<ChildComponent onChange={this.handler} />
)
}
}
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 (
<Button
onClick={() => this.someMethod()}
> Click
</Button>
)
}
}
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
Most of the answers given above are for React.Component based designs. If your are using useState
in the recent upgrades of React library, then follow this answer