React How To, React Tutorial

How to Fetch Data from JSON Files in React and Display It in a Component?

React is a popular JavaScript library for building user interfaces, and Axios is a promise-based HTTP client for making HTTP requests. Together,...

Written by Shivangi Rajde · 3 min read >
Fetch JSON data

React is a popular JavaScript library for building user interfaces, and Axios is a promise-based HTTP client for making HTTP requests. Together, they provide a powerful way to fetch and display data from JSON files in your React applications. In this tutorial, we will walk you through the steps to fetch data from a JSON file using Axios in a React application.

What is JSON?

JSON stands for JavaScript Object Notation. It is a lightweight data-interchange format that is easy for humans to read and write, and easy for machines to parse and generate. JSON is often used to transmit data between a server and a web application or between different parts of an application.

JSON is based on a subset of the JavaScript programming language and uses a simple text format to represent structured data. It consists of two primary structures:

Objects: An object in JSON is an unordered collection of key-value pairs. Each key is a string, followed by a colon, and then a value. Objects are enclosed in curly braces {}. Here’s an example of a JSON object:

{
  "name": "John Doe",
  "age": 30,
  "email": "[email protected]"
}

Arrays: An array in JSON is an ordered list of values. Arrays are enclosed in square brackets []. Each value within an array can be of any valid JSON data type, including objects and other arrays. Here’s an example of a JSON array:

[
  "apple",
  "banana",
  "cherry"
]

JSON supports several data types, including strings, numbers, booleans, null, objects, and arrays. It is commonly used for configuration files, data exchange between a server and a client, and as a data storage and serialization format in various programming languages.

Prerequisites

Before we get started, make sure you have the following prerequisites in place:

  • Node.js and npm: Ensure you have Node.js and npm (Node Package Manager) installed on your computer. You can download them from the official website if you haven’t already.
  • Basic Knowledge of React: Familiarity with React fundamentals will be helpful, but this tutorial will provide step-by-step instructions.

How to fetch data from a JSON file in React?

Let’s look on to the steps for fetching the data from a JSON file in React:

Create a New React Application

If you don’t already have a React application set up, you can create one using the create-react-app command-line tool. Open your terminal and run the following command:

npx create-react-app json-data-fetcher

This command will create a new React project named json-data-fetcher. Navigate to the project directory:

cd json-data-fetcher

Install Axios

Axios is not included by default in a new React project, so you need to install it. Run the following command to install Axios:

npm install axios

Create a JSON File

Create a JSON file that contains the data you want to fetch. For this tutorial, we’ll create a simple JSON file named data.json in the public folder of your project:

// public/data.json
{
  "books": [
    {
      "id": 1,
      "title": "The Catcher in the Rye",
      "author": "J.D. Salinger",
      "isbn": "978-0-316-76948-0",
      "genre": "Fiction",
      "description": "A novel about a disenchanted teenager named Holden Caulfield.",
      "publication_year": 1951,
      "language": "English",
      "cover_image": "catcher-in-the-rye.jpg",
      "total_copies": 5,
      "available_copies": 3,
      "location": "Fiction Section, Shelf A",
      "is_borrowed": false
    },
    {
      "id": 2,
      "title": "To Kill a Mockingbird",
      "author": "Harper Lee",
      "isbn": "978-0-06-112008-4",
      "genre": "Classics",
      "description": "A classic novel set in the American South during the 1930s.",
      "publication_year": 1960,
      "language": "English",
      "cover_image": "to-kill-a-mockingbird.jpg",
      "total_copies": 4,
      "available_copies": 0,
      "location": "Classics Section, Shelf B",
      "is_borrowed": true
    },
    {
      "id": 3,
      "title": "1984",
      "author": "George Orwell",
      "isbn": "978-0-452-28423-4",
      "genre": "Dystopian",
      "description": "A dystopian novel depicting a totalitarian society.",
      "publication_year": 1949,
      "language": "English",
      "cover_image": "1984.jpg",
      "total_copies": 6,
      "available_copies": 6,
      "location": "Science Fiction Section, Shelf C",
      "is_borrowed": false
    },
    {
      "id": 4,
      "title": "Pride and Prejudice",
      "author": "Jane Austen",
      "isbn": "978-1-85326-000-1",
      "genre": "Romance",
      "description": "A classic novel exploring themes of love, class, and society.",
      "publication_year": 1813,
      "language": "English",
      "cover_image": "pride-and-prejudice.jpg",
      "total_copies": 3,
      "available_copies": 1,
      "location": "Romance Section, Shelf D",
      "is_borrowed": false
    },
    {
      "id": 5,
      "title": "The Great Gatsby",
      "author": "F. Scott Fitzgerald",
      "isbn": "978-0-7432-7356-5",
      "genre": "Classics",
      "description": "A novel set during the Roaring Twenties in the United States.",
      "publication_year": 1925,
      "language": "English",
      "cover_image": "the-great-gatsby.jpg",
      "total_copies": 4,
      "available_copies": 2,
      "location": "Classics Section, Shelf A",
      "is_borrowed": false
    },
]

Create a React Component

Now, create a new React component that will fetch and display the JSON data. We are fetching the data on the home page so we will use the component Home.js in the Pages folder of the project:

import React, { useEffect, useState } from "react";
import axios from "axios";

import Card from "react-bootstrap/Card";
import Col from "react-bootstrap/Col";
import Row from "react-bootstrap/Row";

const Home = () => {
  const [books, setBooks] = useState([]);

  useEffect(() => {

    axios.get("/books.json").then((res) => {

      setBooks(res.data.books);
    });
  }, []);

  return (
    <div>
      <h1 className="text-center">List of Books</h1>
      <br />
      <Row xs={1} md={2} className="g-4">
        {books &&
          books.map((book, id) => (
            <Col key={id}>

              <Card key={id}>
                
                <Card.Body>
                  <Card.Title>{book.title}</Card.Title>
                  <Card.Text>{book.description}</Card.Text>
                </Card.Body>
              </Card>
            </Col>
          ))}
      </Row>
    </div>
  );
};

export default Home;

  • We use the useState hook to manage the booksstate and the setBooks function to update it.
  • We use the useEffect hook to fetch the JSON data when the component mounts. The empty dependency array ([ ]) ensures that the effect runs only once after the initial render.
  • The rest of the component uses react bootstrap components for a better User Interface.

Use the Component

Now, you can use the JsonFetcher component in your main application file, such as src/App.js:

// src/App.js
import React from 'react';
import Home from "./Pages/Home";

function App() {
  return (
    <div className="App">
      <Home />
    </div>
  );
}

export default App;

Display fetched data in a React component

The output would look as shown in the image below:

fetching JSON file data
fetching JSON file data

Start the Development Server

To see your application in action, start the development server by running the following command in your project directory:

npm start

This will start the development server, and you should be able to see the fetched JSON data displayed on your application’s homepage.

Conclusion

In this tutorial, you learned how to fetch data from a JSON file in a React application using Axios. Axios simplifies the process of making HTTP requests, and integrating it with React allows you to efficiently fetch and display data from external sources like JSON files. This is a fundamental skill for building dynamic and data-driven React applications.

Loading

Leave a Reply

Your email address will not be published. Required fields are marked *