3

I need a dialog in my react project, but I can't find a good way to implement it. I had searched other implementations, such as react-modal-dialog, react-modal.

but I don't think they do the best way, the most confusing part is the encapsulation.

Take react-modal as the example:

var App = React.createClass({

  getInitialState: function() {
    return { modalIsOpen: false };
  },

  openModal: function() {
    this.setState({modalIsOpen: true});
  },

  closeModal: function() {
    this.setState({modalIsOpen: false});
  },

  render: function() {
    return (
      <div>
        <button onClick={this.openModal}>Open Modal</button>
        <Modal
          isOpen={this.state.modalIsOpen}
          onRequestClose={this.closeModal}
          style={customStyles} >

          <h2>Hello</h2>
          <button onClick={this.closeModal}>close</button>
          <div>I am a modal</div>
          <form>
            <input />
            <button>tab navigation</button>
            <button>stays</button>
            <button>inside</button>
            <button>the modal</button>
          </form>
        </Modal>
      </div>
    );
  }
});

The codes above show the way to use Modal, but you can find that, we have to define the onRequestClose by ourselves every time. I know the reason is, that Modal can be closed by itself or its parent view.

But I want to know, is it better to call Modal.close() in parent view (because of the encapsulation)? If so, could you give me more details of implementation?

1 Answer 1

1

I made my own modal component because I didn't like how they were done. The key thing to remember is that you should be using state as little as possible. The more you can pass things as props, the better. The correct way would be to pass in the modal state from the parent (or a flux store). If you want to see the implementation, look at the source of the component. https://github.com/rackt/react-modal/blob/master/lib/components/ModalPortal.js#L156 < that shows how onRequestClose works.

Edit: Oh yeah, Ryan Florence, the creator of the modal you're using wrote this to me on how modals should work: https://gist.github.com/ryanflorence/fd7e987c832cc4efaa56

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for your answer. After reading the gist, I know this problem is all about the trade off between non-declared and declared state. The other parts of the gist also make sense, maybe I have found the way to rebuild my dialog :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.