Search code examples
ruby-on-railsreactjsreact-rails

Only load React compontent on some pages with react-rails


I have a ReactJS component that I want to mount to #test-scores on user/show.html. The component lives in app/assets/javascripts/react-components/test-score.js.jsx.

How can I make sure it's only loaded when the user visits user/show? It is loaded for every page as it is now.

app/assets/javascripts/react-components.js:

//= require_tree ./react-components

app/assets/javascripts/react-components/test-score.js.jsx

  1 $( document ).ready( function()  {
  2
  3   var TestResultBox = React.createClass({
  4     loadTestScoreFromServer: function() {
  5       $.ajax({
  [snipp...]
 74   React.render(
 75     <TestResultBox />,
 76     document.getElementById('test-scores')
 77   );

This results in a JS error that breaks other things:

react.js?body=1:20238 Uncaught Error: Invariant Violation:
_registerComponent(...): Target container is not a DOM element.

Any suggestions to how I should structure things? :-)

Cheers, Martin


Solution

  • This is a "good error", because it let’s you know that the node doesn’t exist in the DOM before you try to access it. You can easily check if the node exists first, something like:

    var scores = document.getElementById('test-scores')
    if ( scores ) {
        React.render(<TestResultBox />, scores);
    }
    

    jQuery have a bad habit of silenting errors, but if you would like to use jQuery instead, something like this would work:

    $('#test-scores').each(function() {
        React.render(<TestResultBox />, this);
    })