react-rails icon indicating copy to clipboard operation
react-rails copied to clipboard

React with rails issue

Open sunagr1986 opened this issue 10 years ago • 3 comments

I am newby in rails and react project. I have installed all the required gems of react in rails project. when i try to render the request like this

ReactDOM.render( , document.getElementById('container') );

it shows me the error like

Uncaught Error: Invariant Violation: _registerComponent(...): Target container is not a DOM element.

sunagr1986 avatar Jan 25 '16 09:01 sunagr1986

Hi, welcome!

I have a couple suggestions.

  1. Instead of rendering components with ReactDOM.render, how about using the react_component view helper which is provided by react-rails? To use it, do this:

    • Write your React component in /app/assets/javascripts/components/

    • Require your component in application.js with //= require components/my_component

    • In the view, use the react_component helper with the component's name & props. For example,

      <%= react_component("MyComponent",  {my_prop: "my_value"}) %>
      
  2. In your example, there first argument to ReactDOM.render is missing. Where is the component which you want to render?

  3. Make sure the JavaScript runs after #document has been rendered. For example, this does not work:

    <script>document.getElementById("container")</script>
    <div id="container"></div>
    

    but this does work:

    <div id="container"></div>
    <script>document.getElementById("container")</script>
    

    If the JS runs first, it won't find the <div> because it has not been rendered yet!

rmosolgo avatar Jan 25 '16 13:01 rmosolgo

Can two different components rendered through react_component() share state ? Would one re-render if the other changes the state?

lfaire avatar Apr 04 '16 20:04 lfaire

If you're still looking for a way to communicate between unrelated components, have a look at Flux :)

rmosolgo avatar Dec 09 '16 22:12 rmosolgo