intermediate#react#restful-api#javascript
Creating a React App with a RESTful API
Learn how to create a React app that interacts with a RESTful API to fetch and display data.
Introduction
To get started with this tutorial, you'll need to have Node.js and npm installed on your computer.
Step 1: Create a new React app
Create a new React app using create-react-app by running the following command in your terminal:
npx create-react-app react-api-app
Step 2: Create a RESTful API
For this example, we'll use the JSONPlaceholder API.
Step 3: Fetch Data from the API
Create a new file called Api.js and add the following code:
import React, { useState, useEffect } from 'react';
function Api() {
const [data, setData] = useState([]);
useEffect(() => {
fetch('https://jsonplaceholder.typicode.com/posts')
.then(response => response.json())
.then(json => setData(json));
}, []);
return (
<div>
<h1>API Data</h1>
<ul>
{data.map((item, index) => (
<li key={index}>{item.title}</li>
))}
</ul>
</div>
);
}
export default Api;
Step 4: Render the API Component
Open the App.js file and replace the existing code with the following:
import React from 'react';
import Api from './Api';
function App() {
return (
<div>
<Api />
</div>
);
}
export default App;
Conclusion
You now have a React app that fetches and displays data from a RESTful API.