Detailed steps for building a React application with a Rails API

Detailed steps for building a React application with a Rails API

[51CTO.com Quick Translation] What should you do if dynamic data cannot be saved when creating a project using React? To this end, I started looking for a backup API to solve this problem.

In this article, I’ll cover some of the essentials of how to set up and build a Rails API with React as the frontend, in order to help those who find themselves in the same situation as I did.

This article plans to use Rails API as the backend and React as the frontend, so people who need to learn this article follow the same path and steps.

Backend: Rails API part

As a prerequisite before creating a Rails API, it is recommended to configure the database with Postgres because it is easier to deploy than SQLite. Then find and create a new project in your directory by typing:

rails new <app_name> --api --database=postgresql 
cd ` `<app_name>

The --database flag is to select our database engine, here we use Postgresql, and the --api is to create a Rails-based API to use what we need and skip the extra configuration we won’t use.

Open the project using an editor. Then open Gemfile and add rack-cors:

gem 'rack-cors', :require => 'rack/cors'

Then, run `bundle install`

Before you can run your new Rails application, you must first connect it to a database. In the next step, you will connect your newly created Rails application to a PostgreSQL database so that you can store and retrieve recipe data when needed. This step requires input: `rails db:create`

The output will look like this:

Created database 'app_name_development'
Created database 'app_name_test'

Open a terminal and run the following commands to create the controller and model:

rails generate model Movie name rating:integer 
rails generate controller Movies index create update destroy 
rails db:migrate

Next, implement the empty method in the controller to make the API work properly:

Now that we have a controller to manage our models, we will copy some movies into the seed.rb file to display them in the browser and test whether we can convert the data into JSON format. Copy the following movies:

Movie.create(name: "Titanic", rating: 5) 
Movie.create(name: "We were soldiers", rating: 4) 
Movie.create(name: "L'amour quand elle nous tient", rating: 5) 
Movie.create(name: "Nobody's Fool", rating: 2)

After that, paste these four elements into your project and run: rails db:seed

Now you can start writing code. Let's start with routes.rb. If you open that file, you will find routes automatically generated for the controller. Since we will be defining our own routes for the API, we will remove them to define the new routes/API:

Rails.application.routes.draw do 
resources :movies 
end

To view your application, open a browser window and navigate to http://localhost:3000. You will see the Rails default welcome page. But after adding the route, this means http://localhost:3000/movies will get all the movies we have in the database. You can also install any JSON viewer extension on your browser to view the formatted data.

Front-end: React part

Now that we have a basic API, let's use it to set up a front-end React application:

npx create_react-app

Create React App is a project from Facebook that helps you quickly get started with React applications without any configuration.

First, make sure you have Node.js and npm installed. Then, make sure you are outside of the Rails directory and run the following command to create the react app:

npx create-react-app my_react

This will create a React application that communicates with our API. Once you enter cd my_react in the directory and run npm start, it will open at http://localhost:3000.

React Components

One of the main advantages of React is the concept of components, so we create the components we need and delete the components we don’t need as shown below.

In the source directory, we will create a new folder **components** and place the files we want to display in it.

Let's create our first component. Let's create a new file in todo- app/src/components/Movie.js :

import React, { Component } from 'react'; 
class Song extends Component { 
render() { 
return ( 
<div> 
<h1>movies</h1> 
</div> 
); 
} 
} 
export default Song;

This is our component. Next we import it into our application file so that we can display it in the browser.

import './App.css'; 
import Song from './components/Song'; 
function App() { 
return ( 
<div className="App"> 
<Song /> 
</div> 
); 
} 
export default App;

Get API data using axios

It's time to load data from the backend. You can use any package to get/store data. This time we use axios.

Install axios and import it in the Movie component.

npm install axios --save

First initialize the state to an empty array in the constructor:

constructor(props) { 
super(props) 
this.state = { 
movies: [] 
} 
}

Since we have already initialized the state in our component, let's now implement the componentDidMount() method to load our data from the API:

componentDidMount() { 
axios.get('http://localhost:3000/movies') 
.then(response => { 
console.log(response) 
this.setState({movies: response.data}) 
}) 
.catch(error => console.log(error)) 
} 
 
import axios from 'axios'

Remember to import axios:

import axios from 'axios'

At this point you will be blocked by cors and will not be able to get your data. To avoid this you have to use the API in config/appcation.rb:

config.middleware.insert_before 0, Rack::Cors do 
allow do 
origins 'http://localhost:3000' resource '*', :headers => :any, :methods => [:get, :post, :put, :delete, :options] 
end 
end

Now that we know we can get ideas from the API, let's use them in our React components. We can change the render function to iterate over the list ideas from the state and display each of them:

Now that we know we can get ideas from the API, let's use them in our React components. We can change the render function to iterate over the list ideas from the state and display each of them:

render() { 
return ( 
<div> 
 
{this.state.movies.map((movie) => { 
 
return( 
 
<div className="tile" key={movie.id} > 
 
<h2>{movie.name}:<span>{movie.rating}</span></h2> 
 
</div> 
) 
})} 
</div> 
); 
}

Now we can see our data in the browser.

This is the end of this article about using Rails API to build a React application. For more information about using Rails API to build React applications, please search for previous articles on 123WORDPRESS.COM or continue browsing the related articles below. I hope you will support 123WORDPRESS.COM in the future!

You may also be interested in:
  • Detailed explanation of React Native monitoring Android back button and programmatically exiting the application

<<:  Solution to MySQL server login error ERROR 1820 (HY000)

>>:  MySQL 5.7.27 winx64 installation and configuration method graphic tutorial

Recommend

Example of implementing QR code scanning effects with CSS3

Online Preview https://jsrun.pro/AafKp/ First loo...

Customization Method of Linux Peripheral File System

Preface Generally speaking, when we talk about Li...

MySQL 8.0.17 installation and simple configuration tutorial under macOS

If you don’t understand what I wrote, there may b...

Example of creating table statements for user Scott in MySQL version of Oracle

Overview: Oracle scott user has four tables, whic...

Things to note when writing self-closing XHTML tags

The img tag in XHTML is so-called self-closing, w...

Vue button permission control introduction

Table of contents 1. Steps 1. Define buttom permi...

Why can't my tomcat start?

Table of contents Phenomenon: Port usage: Spellin...

Explanation of the usage of replace and replace into in MySQL

MySQL replace and replace into are both frequentl...

Docker installation and deployment of Net Core implementation process analysis

1. Docker installation and settings #Install Cent...

A brief discussion on read-only and disabled attributes in forms

Read-only and disabled attributes in forms 1. Rea...

Practical method of deleting files from Linux command line

rm Command The rm command is a command that most ...

Sample code for implementing two-way authentication with Nginx+SSL

First create a directory cd /etc/nginx mkdir ssl ...