Invoking ReactDom.Render() From Outside of React

We ran into an interesting problem when using a single React component inside of a Rails application. The Rails application has an API and we wanted to render a “Trending Groups” component in our view, but render it using React instead of with a Rails view as a spike into React development. I wrote a simple React app that uses an Ajax request to get the data from the Rails API, but because this was loaded as a stand-alone component inside of a Rails app, the component rendered after the rest of the Dom loaded… Giving a noticeable jolt about 1second after page load.

In React, there are plenty of methods for getting around this jolt in page loading (rendering your component w/o data, using a spinner w/ min-height, etc.), but we wanted to initialize our React component on page load, but then call theReactDom.Render() method — visualizing the component — on demand.

Ultimately this ended up being a lot more simple than we thought… As we had started exploring a react-rails gem, flux and redux examples, and in the end simply wrapping the ReactDom.Render() method in a function, and then making that function available globally using an export solved the problem.

My main App.jsx looks like this:

var React = require('react');
var ReactDOM = require('react-dom');
var GroupCard = require('GroupCard');
function renderGroups() {
<GroupCard />,
module.exports = renderGroups;
window.renderGroups = renderGroups;

We can then call our bundle.js anywhere in the Rails app, like at the top of that view so that it initializes and performs the Ajax request immediately on page load, but then call the function renderGroups() in our view for when we want to render the component, which is outside of the bundled React component.

Interested to see if anybody had their own techniques or ran into this issue, and how you might have solved it.

You can view the example on GitHub.

One clap, two clap, three clap, forty?

By clapping more or less, you can signal to us which stories really stand out.