1

I'm trying to display a simple message inside a react-modal, depending on the parent's state. To keep it simple, I have a button in the Modal, which changes the state of the parent when clicked. It should then show a message on the Modal, but that doesn't happen until I close and reopen the modal.

Here is the dumbed-down version of the code.

var Modal = require('react-modal');

var SomeComponent = React.createClass({
  getInitialState: function() {
    return {
      showMsg: false,
      modalOpen: false
    }
  },
  showMessage: function () {
    this.state.showMsg = true;
  },
  showModal: function () {
    this.state.modalOpen = true;
  }

  render: function () {
    return (
      <div>
        <button onClick={this.showModal}>Show modal</button>
        <Modal isOpen={this.state.modalOpen}>
          <button onClick={this.showMessage}>Show message</button>
          {
            this.state.showMsg ?
              "This is the message"
            :
              null
          }
        </Modal>
      </div>
    )
  }
});

The This is the message will only display after the modal is reopened, but I want it to show while it's open.

Gregor Menih
  • 5,036
  • 14
  • 44
  • 66

1 Answers1

0

In order for your modal to show the message even when your Modal is opened use this.setState() to set the state. It will mutate you state and trigger the re-render of the react component.

var Modal = require('react-modal');

var SomeComponent = React.createClass({
  getInitialState: function() {
    return {
      showMsg: false,
      modalOpen: false
    }
  },
  showMessage: function () {
    this.setState({showMsg: true});
  },
  showModal: function () {
    this.setState({modalOpen: true});
  }

  render: function () {
    return (
      <div>
        <button onClick={this.showModal}>Show modal</button>
        <Modal isOpen={this.state.modalOpen}>
          <button onClick={this.showMessage}>Show message</button>
          {
            this.state.showMsg ?
              "This is the message"
            :
              null
          }
        </Modal>
      </div>
    )
  }
});
Shubham Khatri
  • 270,417
  • 55
  • 406
  • 400