DEV Community

Cover image for How to Use JSON Files in React JS
Sudhanshu Gaikwad
Sudhanshu Gaikwad

Posted on

How to Use JSON Files in React JS

Using JSON files in a React application can streamline data management and enhance the development experience. This guide will walk you through the steps to create a JSON file, integrate it into your React project, and use it as a fake API server.

Step 1: Create the JSON File
First, let’s create a JSON file that contains the data you want to use in your React application.

{
  "title": "Frontend Developer",
  "description": "This is a simple example of using JSON in a React app.",
  "items": [
    {
      "id": 1,
      "name": "Item 1",
      "price": 10.99
    },
    {
      "id": 2,
      "name": "Item 2",
      "price": 14.99
    },
    {
      "id": 3,
      "name": "Item 3",
      "price": 9.99
    }
  ]
}
Enter fullscreen mode Exit fullscreen mode

Step 2: Place the JSON File in Your React Project
To use this JSON file in your React application, place it in the public directory of your React project. This ensures that the file is accessible via a URL when your React app is running. The public directory is typically located at the root of your project structure.

Here is how your project structure might look:

my-react-app/
├── public/
│   ├── data.json
│   ├── index.html
│   └── ...
├── src/
│   ├── App.js
│   └── ...
├── package.json
└── ...
Enter fullscreen mode Exit fullscreen mode

Step 3: Fetch and Use the JSON Data in Your React Component
Now, let’s fetch and use this JSON data in a React component. Here’s an example using the useEffect and useState hooks:

import React, { useEffect, useState } from 'react';

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

  useEffect(() => {
    fetch('/data.json')
      .then(response => response.json())
      .then(data => setData(data))
      .catch(error => console.error('Error fetching data:', error));
  }, []);

  if (!data) {
    return <div>Loading...</div>;
  }

  return (
    <div>
      <h1>{data.title}</h1>
      <p>{data.description}</p>
      <ul>
        {data.items.map(item => (
          <li key={item.id}>
          Name:  {item.name} and Price: ${item.price}
          </li>
        ))}
      </ul>
    </div>
  );
};

export default App;
Enter fullscreen mode Exit fullscreen mode

Step 4: Run Your React Application
Make sure your React application is running by using npm start or yarn start. You should see the data from data.json being displayed in your application.

Top comments (1)

Collapse
 
raajaryan profile image
Deepak Kumar

Hello everyone,

I hope you're all doing well. I recently launched an open-source project called the Ultimate JavaScript Project, and I'd love your support. Please check it out and give it a star on GitHub: Ultimate JavaScript Project. Your support would mean a lot to me and greatly help in the project's growth.

Thank you!