React.js is one of the most popular front-end frameworks nowadays, which lots of people find useful to learn. After mastering the theory, it comes the time to start the practice, and then it may seem a little bit difficult, how to start, how to get data, how to display it. But creating your first React.js application doesn’t have to be so complicated.
In this article, I’m going to create a simple React.js application with fetching data from the API in 5 minutes, step by step.
To create this application, it would be a plus to have basics of React.js, Javascript, HTML, and CSS. Also, to install the tool, I’m going to use you have to install Node.js and npm on your computer.
Let’s start.
1. Install create-react-app
In the beginning, we have to install create-react-app tool. It’s a tool provided by React.js creators, which allows installing ready to use React.js application, with all needed dependencies. To install the tool, we have to use the following command in the command line:
npm install -g create-react-app
After the process finished successfully, you have it installed. Let’s create our app!
2. Create the application
Now, it’s super easy to create our first application using the create-react-app tool. We can do it with a single command in our command line. First, navigate to the folder where you want to have your application through the command line, and then run the following command, where reactapp is the name of our application:
npx create-react-app reactapp
You can feel free to set a different name for your application. If the process finished successful, you should have your folder with the app ready! Let’s start the application now!
3. Start the application
Let’s start our reactapp with the following commands:
cd reactapp
npm start
The first command is used to enter the folder of our application, and the second one starts our app. By default, the application is open at localhost:3000, but we can change the port in the settings.
After the app is started, the browser window will popup at the proper address, and you will see the following image in the browser:
And in your command line you will see the following information:
It seems like our first application is running, now let’s get some data from the API.
4. Creating API call
Let’s open the code of the application in your favorite code editor. Inside the ./src folder, there are our main component App.js. Let’s open it and take a look what’s inside. We can see there the code which we see at https://localhost:3000.
import React from 'react';
import logo from './logo.svg';
import './App.css';
function App() {
return (
<div className="App">
<header className="App-header">
<p>
Edit <code>src/App.js</code> and save to reload.
</p>
<a
className="App-link"
href="https://reactjs.org"
target="_blank"
rel="noopener noreferrer"
>
Learn React
</a>
</header>
</div>
);
}
export default App;
Let’s start by modifying the component to change it into a class component, which will be much more convenient in our case. We want our App.js component looks in the following way:
import React, { Component } from 'react';
class App extends Component {
render() {
return (
<p>Hello world!</p>
);
}
}
export default App;
I removed the App.css and logo.svg imports because we don’t need them anymore. Also, I imported Component from “react”, which I used to create a class component. Let’s add some custom JSX code in return () statement and reload the page to see the result!
Now, let’s set a local state, where we are going to save our data from API.
import React, { Component } from 'react';
class App extends Component {
constructor(props) {
super(props);
this.state = {
posts: []
}
}
render() {
return (
<p>Hello world!</p>
);
}
}
export default App;
I’ve added a constructor and passed props, then I set a local state with posts as an empty array because we are going to get some posts from the API.
Fine, now I’m are ready to create a call to the API. I’m going to use a faked API from the JSONPlaceholder website (https://jsonplaceholder.typicode.com/). To get the data, I’ll use the .fetch method from Javascript. Let’s create a call:
import React, { Component } from 'react';
class App extends Component {
constructor(props) {
super(props);
this.state = {
posts: []
}
}
componentDidMount() {
const url = "https://jsonplaceholder.typicode.com/posts";
fetch(url)
.then(response => response.json())
.then(json => this.setState({ posts: json }))
}
render() {
return (
<p>Hello world!</p>
);
}
}
export default App;
In the code above, I fetched data from the API and saved in our state. Let’s take a look at what is the format of our data before we display our posts:
[
{
"userId": 1,
"id": 1,
"title": "sunt aut facere repellat provident occaecati excepturi optio reprehenderit",
"body": "quia et suscipit\nsuscipit recusandae consequuntur expedita et cum\nreprehenderit molestiae ut ut quas totam\nnostrum rerum est autem sunt rem eveniet architecto"
},
{
"userId": 1,
"id": 2,
"title": "qui est esse",
"body": "est rerum tempore vitae\nsequi sint nihil reprehenderit dolor beatae ea dolores neque\nfugiat blanditiis voluptate porro vel nihil molestiae ut reiciendis\nqui aperiam non debitis possimus qui neque nisi nulla"
},
{
"userId": 1,
"id": 3,
"title": "ea molestias quasi exercitationem repellat qui ipsa sit aut",
"body": "et iusto sed quo iure\nvoluptatem occaecati omnis eligendi aut ad\nvoluptatem doloribus vel accusantium quis pariatur\nmolestiae porro eius odio et labore et velit aut"
},
...
]
5. Displaying the data
Now, we have some posts data, and we would like to display them. To make it good looking without a tone of styling, let’s add Bootstrap CDN to our application. From Bootstrap website, we get a CDN, and we have to place it in ./public/index.html file head section.
....
(html comment removed: Bootstrap )
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
<title>React App</title>
</head>
<body>
....
And that’s it, we can use Bootstrap now. Let’s create a JSX code for our data.
....
render() {
return (
<div className="container">
<div class="jumbotron">
<h1 class="display-4">Blog posts</h1>
</div>
<div className="card">
<div className="card-header">
Featured
</div>
<div className="card-body">
<h5 className="card-title">Special title treatment</h5>
<p className="card-text">With supporting text below as a natural lead-in to additional content.</p>
<a href="#" className="btn btn-primary">Go somewhere</a>
</div>
</div>
</div>
);
}
....
I’ve added a container, header, and a card where I’m going to display the data from this.state.
Let’s use the data with map() method and display them as posts.
import React, { Component } from 'react';
class App extends Component {
constructor(props) {
super(props);
this.state = {
posts: []
}
}
componentDidMount() {
const url = "https://jsonplaceholder.typicode.com/posts";
fetch(url)
.then(response => response.json())
.then(json => this.setState({ posts: json }))
}
render() {
const { posts } = this.state;
return (
<div className="container">
<div class="jumbotron">
<h1 class="display-4">Blog posts</h1>
</div>
{posts.map((post) => (
<div className="card" key={post.id}>
<div className="card-header">
#{post.id} {post.title}
</div>
<div className="card-body">
<p className="card-text">{post.body}</p>
</div>
</div>
))}
</div>
);
}
}
export default App;
We passed data from the posts to a card element and set post.title, post.body, and post.id as a key for an element.
6. Add some styling
We can see our app is almost ready now.
But it still doesn’t look stunning, so we will add some styling. Let’s import an App.css file again, and set there some paddings and margins to make our blog posts look nice.
.app {
padding: 10px;
}
.app .jumbotron {
text-align: center;
}
.app .card {
margin-bottom: 10px;
}
.app .card-header {
color: white;
font-weight: bold;
}
Woohoo! Our app seems to be ready! Fast and easy.
Conclusion
In this article, we created a simple React.js application with fetching data from the REST API. We’ve built a simple listing, displaying short blog posts. We used a create-react-app to set a ready React.js application easily and Bootstrap for styling.
I hope you will find this tutorial helpful and use it as a base for your first React.js application training! If you would like to master your React.js knowledge, join us at duomly.com and complete React.js course!
Have a nice coding!
Thank you for reading!
This article was provided by our teammate Anna.