Search code examples
ruby-on-railsreactjsreact-railsreact-modal

Error on calling react-modal in rails 4 app


I'm having trouble using react-modal in my rails 4 app with a react-rails front end. I have already followed the steps in this SO question How to call react-modal from rails-assets.org in react-rails component and in this GitHub issue https://github.com/reactjs/react-rails/issues/510 but none of them seem to work.

This is the rails-assets gem in my Gemfile

source 'https://rails-assets.org' do
  gem 'rails-assets-react-modal'
end

This is my application.js file

//= require react
//= require ./vendor/react-modal-v1.6.4
//= require react_ujs
//= require react-modal

The //= require ./vendor/react-modal-v1.6.4 call is a call to the compiled file for react-modal. I did this in accordance to the instructions provided in the github issue link above.

Finally, this is my component definition

var ModalTest = React.createClass({
  getInitialState: function() {
    return {
      modalIsOpen: false
    }
  },

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

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

  render: function() {
    return (
      <div>
        <button className="btn btn-primary" onClick={this.openModal}>
          Open Modal
        </button>
        <ReactModal
          isOpen={this.state.modalIsOpen}
          onRequestClose={this.closeModal}
          contentLabel="Modal"
        >
          <h1>Test Modal</h1>
        </ReactModal>
      </div>
    );
  }
});

I am getting the following error on the console:

Uncaught Error: react-modal: You must set an element with Modal.setAppElement(el) to make this accessible

What am I missing? Thanks in advance, guys.


Solution

  • I found an answer from yachaka who posted in this GitHub issue for react-modal.

    The script is loaded before the DOM, resulting in react-modal setting the parent element of the modal to document.body before it exists.

    This can be fixed by adding the lifecycle method componentWillMount as follows:

    componentWillMount: function() {
      ReactModal.setAppElement('body');
    }