1

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 ?

1 Answer 1

1

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).

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.