ORStudios
ORStudios

Reputation: 3233

Accessing Props Value Inside Constructor

I am using the following code to try and set the initial state by accessing the props value. I thought I could do it by accessing the (props) value but It seems to be empty.

constructor(props) {
    super(props);

    //this.renderRowForMain = this.renderRowForMain.bind(this);

    this.state = {
      show: props.showModal,
    };

  }

if I simply place the following insider the render() then it seems to be loading fine.

this.state = {
          show: this.props.showModal,
        };

What I am trying to do is initially set the showModal state to true and then when a close button is tapped change the state to false.

Upvotes: 3

Views: 2245

Answers (2)

Neel Patel
Neel Patel

Reputation: 2176

First of all use props data in constructor like this..

constructor(props) {
super(props);

this.state = {
  show: props.showModal, // true
  };
}

then suppose you want to click button and display state data ...so that we should create click function as like

onClick(){
console.log(this.state.show);  //display show variable data in state in console
}

Whenever you click button then display data in console

And create a button

<button className="button" onClick={() => this.onClick()}>Click Me</button>

Upvotes: 0

Buchanan Henry
Buchanan Henry

Reputation: 86

You should pass in the showModal value in your parent component. Otherwise props.showModal will not show up in your constructor. ​

For example: <MyComponent showModal={true} /> ​ Then, you'll be able to see: ​

constructor(props) {
    super(props);

    this.state = {
      show: props.showModal, // true
    };
}

Hope this helps

Upvotes: 7

Related Questions