How to know the Rails environment in the react JS using webpacker gem?

1.4k views Asked by At

What's the best way to access the Rails.env in javascript?

Currently I am using ReactJS with existing Rails project, using webpacker gem. (Not using react-rails gem)

What I tried?

Set a javascript variable from the rails application (view template where my root component present) and access it in the root component JS. But this approach looks verbose to me as I needed to pass that variable all over the JS files in the react app.

Is there any better way of doing this?

1

There are 1 answers

2
Piotr Galas On

You can use gon gem. Gon allow you to push rails variables to global variables in js.

In controller:

     class SampleController
       def index
         gon.variable_name = variable_value
         ....
       end

and then you can access variable in js this way

      console.log(gon.variable_name)

Another (in my opinion better) solution is query for data you need to another rails action. In your react component you can use componentDidMount for this

componentDidMount(){
   fetch('http://url_to_fetch_data_from_server', {
     method: 'get',
     headers: {
       Accept: 'application/json, text/plain, */*',
       'Content-Type': 'application/json',
       'X-CSRF-Token': 'token get from metatag',
  },
   credentials: 'same-origin',
}).then(response => {
     response.json().then(json =>{
       this.setState(yourData: json.yourData)
     })
  })
}

Then you can send data to all child component via props