Fetch and Display Data From API in React JS

import React, { useState, useEffect } from ‘react’;

const App = () => {
const [data, setData] = useState([]);

useEffect(() => {
fetch(‘https://jsonplaceholder.typicode.com/users’)
.then(response => response.json())
.then(data => setData(data));
}, []);

return (

{data.map(user => (

{user.name}

{user.email}

))}

);
};

export default App;

To fetch and display data from an API in React JS, you can use the fetch function or a library like axios to make an HTTP request to the API, and then use state and JSX to render the data.

How to Retrieve and Display Data From API in React JS

Let’s follow the following steps to fetch/get/retrieve and display data from api in react js app:

  • Step 1 – Create React App
  • Step 2 – Install Bootstrap
  • Step 3 – Create Listing Component
  • Step 4 – Import Listing Component in App.js

Step 1 – Create React App

In this step, open your terminal and execute the following command on your terminal to create a new react app:

npx create-react-app my-react-app

To run the React app, execute the following command on your terminal:

npm start

Check out your React app on this URL: localhost:3000

Step 2 – Install Bootstrap

In this step, execute the following command to install react boostrap library into your react app:

npm install bootstrap --save

Add bootstrap.min.css file in src/App.js file:

import React, { Component } from 'react'

import '../node_modules/bootstrap/dist/css/bootstrap.min.css';

function App() {
  return (
    <div>
      <h2>How to Display Data From API in React JS using fetch()</h2>
    </div>
  );
}

export default App;

Step 3 – Create Listing Component

In this step, create listing.js file. So, visit the src directory of your react js app and create a listing component file named listing .js. And add the following code into it:

import React, { Component } from 'react';


class Listing extends Component {

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

    componentDidMount() {
        fetch('https://jsonplaceholder.typicode.com/users')
            .then(response => response.json())
            .then(records => {
                this.setState({
                    records: records
                })
            })
            .catch(error => console.log(error))
    }

    renderListing() {
        let recordList = []
        this.state.records.map(record => {
            return recordList.push(`<li key={record.id}>{record.name}</li>`)
        })

        return recordList;
    }

    render() {
        return (
            `<ul>
                {this.renderListing()}
            </ul>`
        );
    }
}

export default Listing;

Here is a breakdown of above given code:

  • The first line imports React and a specific part of the React library called “Component”. This allows us to use the React library in our code, as well as create a class that extends the Component class.
  • The Listing class has a constructor function that initializes the state of the component. In this case, it sets the “records” property of the state to an empty array.
  • The componentDidMount function is called after the component is mounted in the DOM. It sends a GET request to the JSONPlaceholder API to retrieve user data. Once the data is returned, it updates the “records” property of the state with the fetched records.
  • The renderListing function is a helper function that takes the records in the component’s state and maps them to an array of HTML list items. The key attribute is used to uniquely identify each list item.
  • The render function returns a JSX element that contains an unordered list element with the result of calling the renderListing function. The JSX syntax allows us to mix HTML-like syntax with JavaScript code.
  • Finally, the Listing component is exported as the default export, which means it can be imported and used in other files.

Step 4 – Import Listing Component in App.js

In this step, import the listing.js file in src/App.js file:

import React, { Component } from 'react';
import logo from './logo.svg';
import './App.css';
import Listing from './Listing'
class App extends Component {
  render() {
    return (
      <div className="App">
        <Listing />
      </div>
    );
  }
}

export default App;

Conclusion

Fetch and display data from APIs in react js; You have learned how to fetch and display data from APIs in react js.

Recommended React JS Posts

Jaspreet Singh Ghuman

Jaspreet Singh Ghuman

Jassweb.com/

Passionate Professional Blogger, Freelancer, WordPress Enthusiast, Digital Marketer, Web Developer, Server Operator, Networking Expert. Empowering online presence with diverse skills.

jassweb logo

Jassweb always keeps its services up-to-date with the latest trends in the market, providing its customers all over the world with high-end and easily extensible internet, intranet, and extranet products.

Contact
Jassweb, Rai Chak, Punjab, India. 143518