To preface my question, I am following this guide.
When trying to build a CRUD interface using Rails and React, I receive this error when trying to create a new item:
addComponentAsRefTo(...): Only a ReactOwner can have refs. You might be adding a ref to a component that was not created inside a component's render method, or you have multiple copies of React loaded.
I wasn't improperly adding a ref
attribute to any JSX not inside of a render
method, so I must have multiple copies of React within my asset pipeline.
Research yielded the following potential results:
//= require react
line from ./app/assets/javascripts/application.js
. This proved to be unsuccessful.//= require react-server
line of the ./app/assets/javascripts/server_rendering.js
file. This lead to a new error, outlined below:Uncaught ReferenceError: $ is not defined
Which I assume means that react_server
not only contains a second copy of React, but also loads something vital for my AJAX calls.
For reference, here are the contents of ./app/assets/javascripts/application.js
:
// This is a manifest file that'll be compiled into application.js, which will include all the files
...
// about supported directives.
//
//= require rails-ujs
//= require react
//= require components
//= require turbolinks
//= require_tree .
and ./app/assets/javascripts/server_rendering.js
:
//= require react_ujs
//= require react-server
//= require ./components
...
Where a set of ellipses, or ...
, are used to shorten known comment sections.
The third potential answer, or removing the //= require react-server
from ./app/assets/javascripts/server_rendering.js
, was a step in the right direction.
Removing this line doesn't yield a new issue, it just reveals another error you had the entire time. react_server
doesn't define the $
variable for AJAX calls, the jQuery gem does.
Found here. I am confident in this solution because the error:
Uncaught ReferenceError: $ is not defined
is a jQuery issue, as the AJAX calls you are probably making take a form referenced in their official doc. here.
Therefore, after running gem install jquery-rails
in your shell, your ./app/assets/javascripts/application.js
should look like this:
...
//= require rails-ujs
//= require jquery
//= require react
//= require components
//= require turbolinks
//= require_tree .
Your ./app/assets/javascripts/server_rendering.js
file should look like this:
//= require react_ujs
// require react-server
//= require ./components
...
Note that require react-server
is commented out.
And make sure to follow the solution found in this SO answer regarding the .\app\views\layouts\application.html.erb
file.