How to integrate React with a Rails/PHP/X backend?

23 May 2017

So you have a classical server-rendered web app in PHP or Rails or something else entirely. You've heard of React — maybe even played with it a little.

You want to add some React superpowers to your existing application. But...

Should I separate the frontend from the backend completely?

Is it a best practice to refactor my app so that it's just an API, and host the React app some place else?

So, should you? or is it?

One of the beauties of React is that you absolutely don't have to buy all-in. Instead of a big-bang rewrite, you can start introducing React where it's the easiest, and gradually work your way through the migration. Migrate the simplest components. Consider making use of React to build a tiny new feature.

Complete rewrites are time- and money-consuming and they may prevent you from tackling new features that you already have in your backlog — and which are more relevant to your users than some rewrite.

Don't listen to people telling you how everything has to be. Be reasonable and do what makes sense in your case.

You may use something like react-rails or a similar library for your web framework, if only as a transitional step. You may find that this will work just fine for you and you might not even need a full-blown SPA. If you do, however, going off react-rails has to be a lot easier than rewriting a sizeable codebase from scratch.

The roadmap could be as follows:

  • use react-rails (or similar library for your web framework), rewrite small things in React, but pass the props in via a helper from react-rails/etc;
  • continue componentizing things;
  • instead of getting props from a helper, make an API endpoint or two and get that to work with some of your components;
  • continue doing that until you're left with a single root react component that renders everything and fetches its data from API;
  • at this point, you may or may not get off react-rails/etc completely and deploy the front-end separately.

Finally, there's an amazing talk by Ryan Florence about switching to React. The example is in Backbone, but the idea is more general and applies to server-rendered HTML or jQuery spaghetti as well!

There is another interesting post about going from PHP to React.

Think your friends would dig this article, too?

If you need a mobile app built for your business or your idea, there's a chance I could help you with that.
Leave your email here and I will get back to you shortly.