If you have created your React app with create-react-app, using the json-loader is the easiest way to import a JSON file in React Js.
In case you haven't, install json-loader by running
Here is the JSON file that I use in this example.
{
"name" : "LearnBestCoding",
"website" : "www.learnbestcoding.com",
"email" : "something@learnbestcoding.com",
"country" :[
{"id": "1", "name" : "USA"},
{"id": "2", "name" : "Canada"},
{"id": "3", "name" : "Japan"},
{"id": "4", "name" : "Australia"}
]
}
Import the JSON file as
import data from './data.json';
export const UsersDetails = () =>{
return(
<>
<div>
<div>Name : {data.name}</div>
<div>Email : {data.email}</div>
<div>Website : {data.website}</div>
<div><label>Country :</label>
<select>
{data.country.map((country) => {
return <option key={country.id} value={country.id}>{country.name}</option>
})}
</select>
</div>
</div>
</>
)
}
interface Country {
id: string
name: string
}
export const UsersDetails = () =>{
let data = require('./data.json');
return(
<>
<div>
<div>Name : {data.name}</div>
<div>Email : {data.email}</div>
<div>Website : {data.website}</div>
<div><label>Country :</label>
<select>
{data.country.map((country: Country) => {
return <option key={country.id} value={country.id}>{country.name}</option>
})}
</select>
</div>
</div>
</>
)
}
Note that if you use Typescript, it will enforce type-checking on the country object.
If your JSON file is hosted externally or located inside the public folder of the project, we can use the fetch() API to access it. This method will not work for JSON files located inside the src folder.
import { useEffect, useState } from "react";
interface Data {
name: string
website: string
email: string
country: [{
id: string
name: string
}]
}
export const UsersDetails = () =>{
const [data, setData] = useState<Data>()
const fetchJson = () => {
fetch('./data.json')
.then(response => {
return response.json();
}).then(data => {
setData(data);
}).catch((e: Error) => {
console.log(e.message);
});
}
useEffect(() => {
fetchJson()
},[])
return(
<>
<div>
<div>Name : {data?.name}</div>
<div>Email : {data?.email}</div>
<div>Website : {data?.website}</div>
<div><label>Country :</label>
<select>
{data?.country?.map((country) => {
return <option key={country.id} value={country.id}>{country.name}</option>
})}
</select>
</div>
</div>
</>
)
}