React JS CRUD – How to fetch data from api in react js & display data in html table
In this tutorial, we will learn how to fetch data from an API in a React JS application and display that data in an HTML table. This is a common task when building web applications, and React makes it easy to perform CRUD operations.
Setting up the project
Before we start, make sure you have Node.js and npm installed on your computer. If not, you can download and install them from Node.js website.
Once you have Node.js and npm installed, you can create a new React project using the following command:
npx create-react-app react-crud-app
After the project is created, navigate to the project folder and install the following dependencies:
npm install axios
Fetching data from an API
For this tutorial, we will use the JSONPlaceholder API, which provides fake data for testing and prototyping. You can access the API from https://jsonplaceholder.typicode.com/posts.
To fetch data from the API, create a new file named Posts.js
in the src
folder and add the following code:
import React, { useEffect, useState } from 'react'; import axios from 'axios'; const Posts = () => { const [posts, setPosts] = useState([]); useEffect(() => { axios.get('https://jsonplaceholder.typicode.com/posts') .then(response => { setPosts(response.data); }) .catch(error => { console.log(error); }); }, []); return ( <div> <h2>Posts</h2> <table> <thead> <tr> <th>ID</th> <th>Title</th> <th>Body</th> </tr> </thead> <tbody> {posts.map(post => ( <tr key={post.id}> <td>{post.id}</td> <td>{post.title}</td> <td>{post.body}</td> </tr> ))} </tbody> </table> </div> ); }; export default Posts;
Save the file and import it into the main App.js
file. You can now display the posts in an HTML table in your React application.
Conclusion
In this tutorial, we learned how to fetch data from an API in a React JS application and display that data in an HTML table. This is the first step in building a CRUD application with React, and it sets the foundation for performing create, update, and delete operations in the future.
Dang, came here cause I thought you would teach how to expose the API, which is the only thing I don't know; it's also the only thing you don't explain. Liked anyway. Informative.
Thanks So much For all of your effort brother really you make me super star in php and laravel really easy and now iam following you in react keep gonig brother you are super awesome
Please upload next video
Hi Brother i want you to make admin panel for movie booking
Please upload next video of this series asap
Sir after this Series plz make an Ecommerce Project in react 18 with Laravel 10 API and also include payment gateway and use Redux Toolkit for state management plz sir plz