Search code examples
ruby-on-railsreactjsreact-railsrails-assets

How to call react-modal from rails-assets.org in react-rails component


I have a rails app that uses react on the front end but I'm having trouble adding other react modules to my components. I am using react-rails for incorporating react into my rails app. I would like to add react-modal to a component. I've used rails-assets to add react-modal as a gem but I'm having trouble calling react-modal in my component. I was hoping it would be a similiar call as React.DOM but that hasn't seemed to be the case.

I can't use the normal 'require()' syntax due to sprockets and I would like to stick with rails-assets rather than browserify/webpack solutions.

So just to be clear I want to display the modal in my component and as of now I get an error returned that says 'Modal is not defined'. Thanks for any help.

This is the rails-assets sourced gem:

### Rails Assets Gems
source 'https://rails-assets.org' do
  gem 'rails-assets-react-modal'
end

Application.js

//= require react
//= require react_ujs
//= require react-modal
//= require components

This is my component:

customStyles = content:
  top: '50%'
  left: '50%'
  right: 'auto'
  bottom: 'auto'
  marginRight: '-50%'
  transform: 'translate(-50%, -50%)'

DOM = React.DOM
@EntityBulkTracker = React.createClass
  displayName: 'EntityBulkTracker'

  getInitialState: ->
    entity: @props.entity
    modalIsOpen: true

  openModal: (e) ->
    @setState modalIsOpen: true

  closeModal: (e) ->
    @setState modalIsOpen: false

  render: ->
    DOM.div null,
      Modal
        isOpen: @state.modalIsOpen
        onRequestClose: @closeModal
        style: "#{customStyles}"

        DOM.h2 null,
          "Hello"
        DOM.input
          type: 'button'
          onClick: @closeModal
        DOM.div null,
          "I am a modal"

Solution

  • When you require a component using sprockets It will be available as a global object, the component will have the same name of the package, e.g:

    If you're using react-modal-bootstrap

    //= require react-modal-bootstrap

    The component available will be:

    <ReactModalBoostrap.Modal />

    It should work the same for the modal you're using, so instead of using <Modal /> you should be using <ReactModal.Modal />

    Also remember to restart your server after you run bundle install