0
How do I catch a state of a child component?
In my example I have Shell.js which is the parent component:
class Shell extends Component {
render() {
return (
<div>
<Nav propsdaNav={1} />
<SupermarketDetail />
</div>
);
}
}
export default Shell;
I want to get the state
of the component <SupermarketDetail />
and apply the return as props
in the component <Nav />
instead of number 1.
Supermarketdetail.js is like this:
class SupermarketDetail extends Component {
constructor(props) {
super(props);
this.state = {
detailState: 0
}
}
handleState(number) {
this.setState({ detailState: number });
}
componentDidMount() {
this.handleState(1)
}
componentWillUnmount() {
this.handleState(0)
}
render() {
return (
<div className="containerDetail">
....
</div>
);
}
}
export default SupermarketDetail;
I wanted to receive in the father component this detailState
. Any idea?
You can set the state in the parent component, create a method in the parent that updates that state and pass via props to the child.
– NoobSaibot
React - How to modify a parent component state from the child?
– NoobSaibot
An example: https://stackblitz.com/edit/react-v7jeqm
– NoobSaibot
Similarly, I would need the information that comes from the child component
– Lucas Fieri
From son to father will not be possible ( as far as I know ) if not as already commented. In your method
handleState
execute the parent method by passing as parameternumber
.. More would be better to create the state in the parent, so avoid code duplication.– NoobSaibot