How to load/import a JSON file in React
In this tutorial, we are going to learn about how to load or import a JSON file in the React app.
Consider, we have this users.json
file in our react app.
[
{
"id": 1,
"name": "John"
},
{
"id": 2,
"name": "Pen"
},
{
"id": 3,
"name": "Lara"
}
]
Now, we are loading this above JSON file into the react component.
Loading the JSON file
We can load a JSON file into the react component, just like how we import JavaScript modules or CSS modules using the es6 import
statement.
import React from "react";
import Users from "./users.json";
export default function App() {
return (
<div className="App">
<h1>Users list</h1>
{Users.map(user => ( <li key={user.id}>{user.name}</li> ))} </div>
);
}
In the above code, we first imported the users.json
file as a Users
JSON array and rendered it into the dom by using the JavaScript map()
method.