skip to Main Content

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


  1. 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:

    export default class App extends React.Component {
      constructor(props){
        super(props);
        this.state = {
          show: true
        }
      }
    
      const toggleDisplay = () => {
        this.setState({ show:!this.state.show });
      }
    
      render() {
        return (
          <div className="App">
            {this.show && <ChildrenUnmounting onclickfun={toggleDisplay} />}
          </div>
        );
      }
    }
    
    class ChildrenUnmounting extends React.Component {
      constructor(props) {
        super(props);
        alert("constructor is called!");
      }
    
      render() {
        return (
          <>
            {alert("render is called!")}
    
            <h1>This content is shown!</h1>
            <button onClick={this.props.onclickfun}>
              Toggle View
            </button>
          </>
        );
      }
    
      componentWillUnmount() {
        alert("componentWillUnmount is called!");
      }
    }
    
    
    Login or Signup to reply.
  2. In your Appcomponent’s render() method, you are using this.show instead of this.state.show. Update the line

    {this.show&&<ChildrenUnmounting onclickfun={toggleDisplay} />} 
    

    to

    {this.state.show && <ChildrenUnmounting onclickfun={toggleDisplay} />}.
    

    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.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search