Skip to content

Instantly share code, notes, and snippets.

@elvisgiv
Last active April 30, 2018 13:40
Show Gist options
  • Save elvisgiv/96a66175ac9903780f26d2d92a522dc5 to your computer and use it in GitHub Desktop.
Save elvisgiv/96a66175ac9903780f26d2d92a522dc5 to your computer and use it in GitHub Desktop.

задача - подключить react к существующему проекту на rails

in Gemfile

# for react
gem 'webpacker', '~> 3.4'

installing Webpacker

bundle exec rails webpacker:install
# then in a existing Rails app already setup with Webpacker run this
bundle exec rails webpacker:install:react 

this will create javascript folder with packs subfolder and two files application.is and hello_react.jsx

in view

importing react components in any view, what do you need

#index.html.haml
...
  #some_id
    = javascript_pack_tag 'hello_react'

in hello_react.jsx

turn on code in this file, if element with id=some_id exists

import React from 'react'
import ReactDOM from 'react-dom'
import PropTypes from 'prop-types'

const Hello = props => (
  <div>Hello {props.name}!</div>
)

Hello.defaultProps = {
  name: 'David'
}

Hello.propTypes = {
  name: PropTypes.string
}

document.addEventListener('DOMContentLoaded', () => {
  ReactDOM.render(
    <Hello name="test" />,
    document.getElementById('some_id'))
})

in controller

method should return json if we want invoke them in react component

example invoke API method rails from react

...
  checkNodeInfo() {
    const url = '/node-info';
    let self = this;
    fetch(url)
      .then((resp) => resp.json())
      .then(function (data) {
        self.setState({
          nodeInstalled: self.isNodeInstalled(data),
          nodeInfo: data,
          loaded: true
        })
      })
      .catch(function (error) {
        console.log(error);
      });
  }
...
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment