EPeak Daily

How one can create a Rails challenge with a React and Redux front-end

0 8


This tutorial will present you how you can create a single-page app with React (and Redux and Semantic UI) inside a Rails challenge.

This tutorial may even embody:

Aspect notice #1. I noticed this fantastic information lately and it impressed me to write down one for Rails.

Aspect notice #2. Right here is the completed tutorial. The commit historical past corresponds (sort of) with the steps on this information.

Overview

To present you a way of what we’re going to construct and the way issues will work, see the two diagrams beneath.

Diagram 1: Dealing with the primary HTTP request (i.e. requests from the browser to our Rails App)

The diagram beneath illustrates your React App inside your Rails challenge, and the trail (stable black line) that the primary request takes to return the React App again to the consumer (browser).

Diagram 2: Dealing with subsequent HTTP requests (i.e. requests from our React App to our Rails App)

After the React App is loaded within the consumer’s browser, the React App shall be answerable for sending requests to your Rails App (stable black line). In different phrases, as soon as React is loaded, requests to Rails will come from Javascript code, and never the browser.

Different Essential notes earlier than we begin coding

  • Consider your React App as being separate out of your Rails App. The React App is strictly for the front-end and runs within the consumer’s browser. The Rails half is strictly for the back-end and runs on the server. The Rails App doesn’t know something concerning the React App aside from when to return its static property (Webpack compiled HTML, JS, and CSS).
  • As soon as your React App is loaded by your browser, all of the logic to make HTTP requests (retrieve knowledge, and switch that knowledge right into a view) is finished within the front-end (i.e. browser).
  • Your Rails App successfully doesn’t serve any views aside from the one which serves your React App. On this tutorial, the one Rails view is /app/views/static/index.html.erb
  • All /api/* paths will get dealt with by the Rails App, whereas all different paths will get dealt with by React contained in the browser (after your browser has loaded the primary request). For instance, http://your-app.com/one thing shall be despatched to the Rails App, after which returned again to your React App (the HTML/JS/CSS that has already loaded within the browser), which can determine what to point out on the display screen.
  • Issues for constructing a single-page app. Not vital for this tutorial however helpful.
  • React Part design patterns. Once more, not vital however helpful.

System Necessities

FYI right here’s my system config. Not saying you want this, however one thing related will make this tutorial expertise smoother.

  • macOS 10.13.6 (Excessive Sierra)
  • Ruby 2.5.1
  • Rails 5.2.1 (and Bundler 1.16.6)
  • – gem set up bundler -v 1.16.6
  • Node 9.8.0

Lastly, on to the code!

Step 1: Create a brand new Rails challenge with Webpack and React

Create a brand new Rails app. I’ve named mine rails-react-tutorial.

rails new rails-react-tutorial --webpack=react

See right here for more information on the --webpack=react flag launched in Rails 5.1.

Step 2: Be certain that the Webpacker and React-Rails gems are put in

Examine if the Webpacker and React-Rails gems are in your Gemfile. If the gems should not there, then add it:

Typically solely Webpacker is added, and never React-Rails; undecided why …

Now run these instructions to put in all the things.

bundle set up
# This command won't be vital.
# If already put in, then it can
# ask you to override some information.
rails webpacker:set up
rails webpacker:set up:react  
rails generate react:set up
yarn set up

Now run rails server -p 3000 and go to http://localhost:3000 to verify our challenge is working.

Professional Tip #1: run ./bin/webpack-dev-server in a separate window whereas coding to have any modifications routinely construct and reload the browser.

Professional Tip #2: If you happen to get this error can’t activate sqlite3 (~> 1.3.6), already activated sqlite3–1.4.0 then add gem ‘sqlite3’, ‘~> 1.3.6’ to Gemfile. See this hyperlink for more information.

Step 3: Add a Controller class, and Route, to our Rails app

Add a brand new path to our Rails app. For this instance, we’ll add GET /v1/issues endpoint to config/routes.rb`.

Our config/routes.rb file

This new route would require a ThingsController. Create a brand new app/controllers/v1/things_controller.rb file. Keep in mind, it ought to be within the v1 folder as a result of it belongs to our Rails API.

Our /app/controllers/v1/things_controller.rb file

Our Issues controller will return a hard-coded response for GET /v1/issues.

At this level, you need to have the ability to re-run rails server -p 3000 and go to http://localhost:3000/v1/issues.

Success!

Subsequent, we’ll create a brand new React part.

Step 4: Generate a brand new React part

Create a HelloWorld React part that accepts a String parameter named greeting by working the next command:

rails generate react:part HelloWorld greeting:string

A file ought to be created: app/javascript/parts/HelloWorld.js.

Our app/javascript/parts/HelloWorld.js file

Step 5: Use our HelloWorld part

To make use of and see our new HelloWorld part we have to 2 issues: create a view embeds this part, and add a path to level to this view.

To create a view, create the file app/views/static/index.html.erb and add the next:

“Good day” is being handed in because the “greeting” param for HelloWorld

For our new route, add the next line to our routes.rb file, and an empty StaticController to assist it.

Including a path to serve our new view that comprises the HelloWorld part

Add this to app/controllers/static_controller.rb:

An empty controller

You must now have the ability to re-run rails server -p 3000 and go to http://localhost:3000/ to see your new React part (bear in mind to run ./bin/webpack-dev-server in a separate window to have an Javascript modifications routinely get packaged by webpack).

Success! Our first rendered part.

Now that we’ve a React part that renders in our view, let’s develop our app to assist a number of views with react-router.

Step 6: Add React-Router

First, run this command so as to add react-router-dom, which incorporates and exports all of react-router and a few extra helper parts for net shopping. Extra information right here.

npm set up --save react-router-dom
yarn set up

This command ought to add the next line to your bundle.json file. Notice, 4.2.2 was used right here, however your model could possibly be totally different.

Now let’s use React Router to make some routes for our React Entrance-Finish.

Step 6: Utilizing React-Router

react-router permits us to handle all our UI routes strictly with Javascript. Which means we’ll want a single “App” part that encapsulates our whole utility. “App” may even use React-Router to current the proper “Web page” part for the URL being requested.

To begin, run this command so as to add an App part that may symbolize our whole front-end utility.

rails generate react:part App

Subsequent, open the file for the newly created React part, app/javascript/parts/App.js, and add the next …

Our React App with 2 routes

Now change index.html.erb to level to our new App part.

The App part will encapsulate our whole front-end.

Lastly, edit your routes.rb to have Rails ship all requests that aren’t for the API to our App part (by way of StaticController#index).

Our routes.rb now forwards all non-API and non-Ajax requests to our React App

We will now run rails server -p 3000 and go to http://localhost/ and http://localhost/hiya to see React-Router working (bear in mind ./bin/webpack-dev-server allows auto-webpacking).

Subsequent, we’ll want to put in some extra dependencies earlier than we are able to join our React front-end to our Rails API.

Step 7: Including Redux, Sagas, Babel Polyfill, and Axios

Now let’s add the next Javascript libraries for our front-end.

  • Redux to handle the worldwide state of our utility.
  • Babel-Polyfill to allow fancy Javascript options that may not in any other case be out there on older net browsers.
  • Reselect and React-Redux to make working with Redux simpler.

To put in all the things, run the next:

npm set up --save redux babel-polyfill reselect react-redux
yarn set up

Now we’ll use these instruments to arrange a Redux State Retailer, then add some Actions and Reducers to make use of it.

Step 8: Arrange Redux State Retailer

On this step, we’ll arrange the Redux State Retailer for our app with the next template (we’ll add and take away “issues” within the subsequent steps).

{
"issues": [
{
"identify": "...",
"guid": "..."
}
]
}

First, create a configureStore.js file. It will initialize our Redux Retailer.

Code to initialize our Redux State, and our first Reducer!

Now import and use configureStore() within the App Part to create a Redux State and hook it as much as our App.

Initializing the Redux State for our App

Now you’ve got Redux put in in your app! Subsequent, we’ll create an Motion and a Reducer, and start to write down and skim from our Redux State.

Step 9: Add an Motion and a Reducer

Now that the App has a Redux State, we’ll add a <button> to HelloWorld that dispatches an Motion (that we are going to outline right here) that shall be acquired by the rootReducer().

First, add getThings() Motion definition and import createStructuredSelector() and join() into theHelloWorld Part. This maps components of the Redux State, and Actions (i.e. dispatching getThings()) , to HelloWorld’s prop.

Subsequent, add a <button> to HelloWorld that dispatches a getThings() Motion (from ./actions/index.js) on each click on.

HelloWorld part with all some new Redux helper code

After all the things is added to HelloWorld, go to http://localhost:3000/hiya, open the Console, and click on the “getThings” button to see your Motion and Reducer features being referred to as.

Have a look at the console.log() output to see our Motion being dispatched

Now you could ship an Motion that may be acquired by a Reducer, let’s have the Reducer alter the Redux State.

Step 10: Have HelloWorld learn React State and show “issues”

Insert a Record <ul> in HelloWorld and fill it with “issues” out of your Redux State.

HelloWorld with <ul> that reads “issues” from our Redux State

To check if that is really working, we are able to initialize with some “issues” knowledge. As soon as that is executed, we are able to refresh the web page and see it in our checklist.

Initialize our Redux State with some “issues” to see if the front-end <ul> is studying it correctly

Now that we’ve a easy Motion and Reducer working, we’ll lengthen this in order that the Motion queries our Rails API and the Reducer units the content material of “issues” with the API response.

Step 11: Set up Redux-Thunk

We’ll want Redux-Thunk to permit async workflows (like an HTTP request) to dispatch Actions.

Set up redux-thunk by working this command:

npm set up --save redux-thunk
yarn set up

Now, let’s use Thunk in our Motion!

Step 12: Use redux-thunk and fetch() to question API and set React State with outcomes

First, let’s import redux-thunk in configureStore.js and set up it our Redux Retailer so our App can deal with “Thunk” Actions.

Want to put in Redux Thunk as a Redux middleware in our App.

Now take a look at that all the things is working by beginning the App and loading a web page.

Subsequent, let’s change the getThings() Motion to return a perform that performs the next (as an alternative of returning the Motion object):

  1. Dispatch the unique Motion object
  2. Make a name to our Rails API.
  3. Dispatch a brand new Motion getThingsSuccess(json) when the decision succeeds.

For this step, we may even want so as to add the getThingsSuccess(json) Motion.

Our new getThings() Motion perform that does much more than returning a easy object — because of Redux Thunk!

After all, this does nothing to the Redux State since our Reducer just isn’t making any modifications. To repair this, change the Reducer to deal with the GET_THINGS_SUCCESS Motion and return the brand new State (with the response from the Rails API).

Have our Reducer change the Redux State when GET_THINGS_SUCCESS is dispatched

Now should you begin your App, navigate to localhost:3000/hiya and click on the button, your checklist ought to change!

There you’ve got it. A Rails API hooked as much as a React+Redux App.

(Bonus) Step 13: Putting in Redux Dev Instruments

Possibly I ought to’ve put this step earlier, however Redux Dev Instruments is important for debugging the Actions your App is sending, and the way these Actions are altering your State.

That is how you put in it. First, set up the right extension in your browser (Chrome, Firefox).

Subsequent, run the next to put in the library.

npm set up --save-dev redux-devtools-extension
yarn set up

Now, use it to initialize your Redux State Retailer.

Set up Redux Dev Instruments in your App. You have to to do some further modifications to show this off in manufacturing mode.

In spite of everything that is executed, you need to have the ability to see a brand new tab, Redux, in your Chrome (or Firefox) dev instruments, that allows you to see which Actions had been dispatched, and the way every one modified the App’s State. The React tab may even present you all of your parts and their props and states.

Debugging React Elements and Redux State/Actions will get 100x simpler with this

Pleased debugging!

(Bonus) Step 14: Semantic UI

Semantic is a superb library for UI parts that makes it very easy to construct good trying web sites shortly.

To put in this library, run the next.

npm set up --save semantic-ui-css semantic-ui-react
yarn set up

Add this to app/javascript/packs/utility.js:

import 'semantic-ui-css/semantic.min.css';

And add this to app/views/static/index.html.erb:

<%= stylesheet_pack_tag "utility", :media => 'all' %



Supply hyperlink

Leave A Reply

Hey there!

Sign in

Forgot password?
Close
of

Processing files…