Reputation: 1268
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?
Upvotes: 1
Views: 1414
Reputation: 4776
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
Upvotes: 1