JSON (JavaScript Object Notation) is a lightweight data-interchange format that is easy for humans to read and write, and easy for machines to parse and generate. It is often used to transmit data between a server and web application in a structured format.
Sometimes in the apps we build, we need to use stoppers to replace the backend called by our react code.
This is where the JSON file containing the data to be returned by the backend comes into play. In this article, I’ll show you how you can read a JSON file in your React component.
How to Read a JSON file
First thing first, you have to create a new react project
npx create-react-app your-react-app
Once the npx command has finished to run, you will have a basic react app structure which will look like this
my-app/
README.md
node_modules/
package.json
public/
index.html
favicon.ico
src/
App.css
App.js
App.test.js
index.css
index.js
logo.svg
Now we will add the data.json file in the public directory
public/
index.html
favicon.ico
data.json
In the data.json file, add the following snippet
[
{ "category": "Fruits", "price": "1", "name": "Apple" },
{ "category": "Fruits", "price": "1", "name": "Dragon fruit" },
{ "category": "Fruits", "price": "2", "name": "Passion fruit" },
{ "category": "Vegetables", "price": "2", "name": "Spinach" },
{ "category": "Vegetables", "price": "4", "name": "Pumpkin" },
{ "category": "Vegetables", "price": "1", "name": "Peas" }
]
Now in the react component, let say your App.js
, you can use the fetch API to retrieve the data in your react component
import './App.css';
import {useEffect, useState} from "react";
function App() {
const [data, setData] = useState([]);
useEffect(() => {
fetch(process.env.PUBLIC_URL + '/data.json')
.then(response => response.json())
.then(jsonData => setData(jsonData))
.catch((error) => console.error('Error reading JSON file →', error));
}, []);
console.log(data)
return (
<div className="App">
{/* use the JSON data here */}
</div>
);
}
export default App;
The console.log(data) will show all the content of the JSON file, and the process.env.PUBLIC_URL
will point to the public directory.
Now you can run the app with the following command.
npm start
I hope you enjoyed reading this, and I'm curious to hear if this tutorial helped you. Please let me know your thoughts below in the comments. Don't forget to subscribe to my newsletter to avoid missing my upcoming blog posts.
You can also find me here LinkedIn • Twitter • GitHub or Medium
Wrapping Up
In summary, the ability to read the content of a JSON file in a React component is useful for integrating data, communicating with APIs and customizing application settings.
Get the code source here in my GitHub account 👇🏽