How to Get Data and Display from API in React JS?
Sep 15, 2022 . Admin
Hi Artisan,
This detailed guide will cover react js get data from api. you will learn how to fetch data from api and display in react js. This tutorial will give you a simple example of react fetch data from api functional component. This article will give you a simple example of how to display data from api in react js. follow the below example for how to fetch data from api in react using axios.
In this example, i will show you how to get and display data in React JS App. we will install axios using npm command. Then we will use "jsonplaceholder" demo api for get request. we will create simple table with ID, Name, Email and City and get data from get request.
So, let's see follow the below step to create simple example with axios get request.
Step 1: Create React JS AppIn this step, open your terminal and execute the following command on your terminal to create a new react app:
npx create-react-app react-axios-exampleStep 2: Install Axios npm Package
In this step, we need to install axios npm package to use their functions. let's run below command:
npm install axiosStep 3: Install Bootstrap
In this step, we will install bootstrap npm package to use design css. let's run below command:
npm install bootstrap --saveStep 4: Create UsersList.js Component
Here, we will create UsersList.js component and make table. Then call axios get request by on load. so let's update code on following file.
src/UsersList.jsimport React from 'react' import axios from 'axios'; class UsersList extends React.Component{ state = { users: [] } componentDidMount() { axios.get(`https://jsonplaceholder.typicode.com/users`) .then(res => { const users = res.data; this.setState({ users }); }) } render(){ return( <div> <div class="row"> <div class="col-md-6 offset-md-3"> <br /><br /> <h3>Users List</h3><br /> <table class="table table-bordered"> <tr> <th>No</th> <th>Name</th> <th>Email</th> <th>City</th> </tr> { this.state.users ? this.state.users.map((user,i)=> <tr> <td>{++i}</td> <td>{user.name}</td> <td>{user.email}</td> <td>{user.address.city}</td> </tr> ) : null } </table> </div> </div> </div> ) } } export default UsersList;Step 5: Update App.js File
Here, we will update our App.js file code. we will import UsersList component and import bootstrap for design. so let's update code on App.js file.
src/App.jsimport './App.css'; import '../node_modules/bootstrap/dist/css/bootstrap.min.css'; import UsersList from './UsersList'; function App() { return ( <div class="container"> <h2>React JS Axios GET Request Example - MyWebTuts.com</h2> <UsersList /> </div> ); } export default App;Step 6: Run React JS App
In the last step run your project using bellow command.
npm startOutput
I hope it can help you...