0

I have this code and for some reason when toggle gets called console gives undefined for 'this.state.' Not really sure what's going on with it.

// Toggles the modal to open or close depending on current state
  toggle() {
    console.log(this.state);
    this.setState({
      showModal: !this.state.showModal
    });
  };

Down in Render

<Modal isOpen={this.state.showModal} toggle={this.toggle}>
  <ModalHeader toggle={this.toggle}>Modal title</ModalHeader>
  <ModalBody>
    Lorem ipsum dolor sit amet
  </ModalBody>
  <ModalFooter>
    <Button color="primary" onClick={this.toggle}>Save</Button>
    <Button color="secondary" onClick={this.toggle}>Cancel</Button>
  </ModalFooter>
</Modal>
Taki
  • 17,320
  • 4
  • 26
  • 47
Gooby
  • 621
  • 2
  • 11
  • 32
  • Try making `toggle` an arrow function – Frank Modica Jan 16 '19 at 18:38
  • there are many, many Stack Overflow questions regarding unexpected behavior inside React event listeners. Have you tried any of the solutions mentioned in any of them, and if not then please add a little more detail to your question as to why they might not apply here. – Dan O Jan 16 '19 at 18:46

2 Answers2

0

that is because, this refers to the callee's scope, hence doesn't refer to the state as you would expect it to. Bind the method to this in the constructor or use an arrow function.

toggle = () => {
  console.log(this.state);
  this.setState({
    showModal: !this.state.showModal
  });
};
Danyal Imran
  • 2,515
  • 13
  • 21
0

it's because toggle() has it's own this and therefore doesn't have a state, you can either use an arrow function like :

toggle = () => {
    console.log(this.state);
    this.setState({
      showModal: !this.state.showModal
    });
  };

Or bind it in the constructor

constructor(props){
  super(props);
  this.toggle = this.toggle.bind(this);
}
Taki
  • 17,320
  • 4
  • 26
  • 47