export default class App extends React.Component {
constructor(props){
super(props);
this.state={
show:true
}
}
render() {
const toggleDisplay=()=>{
this.setState({show:!this.state.show});
}
return (
<div className="App">
{this.show&&<ChildrenUnmounting onclickfun={toggleDisplay} />}
</div>
);
}
}
class ChildrenUnmounting extends React.Component {
constructor(props) {
super(props);
alert("constructor is called!");
this.state={
onclickfun:props.onclickfun,
}
alert("constructor is called!");
}
render() {
return (
<>
{alert("render is called!")}
<h1>This content is shown!</h1>
<button onClick={this.state.onclickfun}>
Toggle View
</button>
</>
);
}
componentWillUnmount() {
alert("componentWillUnmount is called!");
}
}
I was trying to use the componentWillMount functionality of react and to change the value of a prop from child component by click event. I think I am willing to use the "lift the state up" and want to use the componentWillMount property of React.
2
Answers
You’re not properly passing down the state setter down to the child component. Instead, you’re setting it to a state value/variable.
Here how the code should be:
In your Appcomponent’s render() method, you are using this.show instead of this.state.show. Update the line
to
With this change, the show state property will be properly referenced in the render() method and the child component will be shown or hidden based on its value.