Our JSON File place Inside Public Folder In React.js Project. ReactJS Public Folder Access By URL.
JSON File Structure Most Important For Us, Because when JSON Data Warp Inside Array. In case You Use Map() Method And Get Data Easily Inside Your Project.
[
{
"username": "officialrajdeepsingh",
"firstName": "Rajdeep",
"lastName": "Singh",
"gender": "Male",
"aboutAuthor": "Read Book, Music Lover and Web Developer"
},
...
]
You Write Directly Inside JSON File You Use Object.entries() Method
Firstly, after use map() method For Read JSON File. Rest Of Code Same In My Demo
Project.JSON data Access Not Easily In Object.entries()
Method. I'm Recommend You To Wrap Your JSON Data Firstly Inside the Array.
{
"username": "officialrajdeepsingh",
"firstName": "Rajdeep",
"lastName": "Singh",
"gender": "Male",
"aboutAuthor": "Read Book, Music Lover and Web Developer"
}
// react
import React, { useState } from 'react';
// Own Css
import './styles.css';
export default function App() {
// react Hook For State Handler
const [data, setData] = useState(null);
// Fetch Function
fetch('./data.json').then(
function (res) {
return res.json();
},
).then(function (data) {
// store Data in State Data Variable
setData(data);
}).catch(
function (err) {
console.log(err, ' error');
},
);
return (
<div className='App'>
{
// use data State Variable For Get Data Use JavaScript Map Mathod
data
? data.map(
function (data) {
return (
<div className='card'>
<h4>{data.username}</h4>
<h2>{data.firstName} {data.lastName}</h2>
<h3>{data.gender}</h3>
<h3>{data.aboutAuthor}</h3>
</div>
);
},
)
: ''
}
</div>
);
}
./public/data.json
.http://your-react-server-port/data.json
https://7v6ny.csb.app/data.json
https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API https://www.geeksforgeeks.org/javascript-fetch-method/