user3814030
user3814030

Reputation: 1283

read rails variable on react code

How can I read a rails variable on a react component.

On my controller

@test = 'test'

On my react component

var test = "<%= @test %>"
console.log(test)  // outputs ''

Is what I am trying to do possible ?

Upvotes: 1

Views: 500

Answers (1)

Alexa Y
Alexa Y

Reputation: 1854

Javascript files aren't rendered in the same manner that erb files are. What you see is what you get for the most part.

If you want to serve up variables from the server that can be read by react, there are a couple of options.

  • In an html.erb view, create a script tag and populate it with the data

    <script>var test = <%= @test %>;</script>

  • Create an endpoint which will respond with a JSON representation of the data. This would require the javascript to perform an ajax call to said endpoint upon the document being ready (or componentDidMount in react).

Upvotes: 1

Related Questions