3

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.

ORStudios
  • 3,157
  • 9
  • 41
  • 69
  • it looks like initially the `prop showModel` is blank or not having the value, to check that use `console.log(props.showModel)` inside `constructor` and see the result. – Mayank Shukla May 11 '17 at 16:33
  • Inside the IOS simulator how do I access console.log? – ORStudios May 11 '17 at 16:34
  • don't know about that, you can use alert also. check this, how to check console in ios simulator: http://stackoverflow.com/questions/10165641/how-can-i-get-the-console-logs-from-the-ios-simulator – Mayank Shukla May 11 '17 at 16:35
  • in the simulator, hit command + D then you can access the console through the chrome window – Matt Aft May 11 '17 at 17:20

2 Answers2

7

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

fnatic_shank
  • 572
  • 6
  • 12
0

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>
Neel Patel
  • 2,028
  • 18
  • 17