I recently wrote about real-world results with React JS. Here is a concrete example of adding React to a Rails app, start to finish.
At Cook Smarts, we want recipes to be consistent, so we provide administrators with suggested ingredient names. That way, a red bell pepper is always called a red bell pepper.
Suggestions are populated from previous recipes automatically, but they need to be pruned by an administrator to make sure they’re accurate.
The app needs to provide an Excel-like way to quickly prune suggestions.
React JS, in under 150 lines of readable code, gets us exactly what we need, an Excel-like data editor.
Our server actions in Rails
A Rails controller provides JSON data to the view and processes edits and deletions to the database.
Our data model in Fluxxor
A typical React implementation includes a data model, or store, which manages data and the actions that can be taken on the data. At a Cook Smarts, we use Fluxxor, inspired by Facebook’s Flux concept.
The object contains the store itself, instantiated through Fluxxor’s createStore method.
The object also contains the store’s actions, which communicates with the simple API we defined in the Rails controller:
Finally, the object includes a method for creating a Flux object containing the store and its actions. The Flux object is passed to the React-based UI in the next section.
Our UI in React
So far, we have covered the server-side API and the client-side data store. We still need to build our client-side UI, and that’s where React comes in.
React apps are basically component trees. The ingredient suggestions editor contains multiple ingredient suggestions,, so our component tree at its simplest is:
The IngredientSuggestionsEditor component is the parent, and watches the Flux store for any changes (see code comments):
The component above renders an IngredientSuggestion component for each ingredient. The IngredientSuggestion component shows the name of the ingredient and allows the user to edit it (see code comments):
Tying it all together
The global function creates the Fluxxor store and renders React components to the page. Here is its code, excluding the snippets we’ve already covered:
The Rails view containing the suggestion editor runs the global function on page load, passing all the ingredient suggestions in JSON format, which we passed to the view from the Rails controller:
Here’s the full code for the Rails controller, Rails view, Fluxxor store/actions, and React components.
React allowed us to get a client-side interface up and running in a couple of hours. React presents few surprises and operates consistently. It’s no wonder that it powers much of Facebook and Instagram, two sites that have to work for a wide array of users.
Hired.com brings Rails job offers to you. Free for candidates. Salaries from $75,000 to $250,000. Sign up now!