There are several ways to import JSON data within a React component:
- Use ES6 imports and exports
- Add the JSON data in a file within your
public
folder, assuming you initialized your project with Create React App, then fetch said data within your componentDidMount()
method, and lastly add the fetched data to your component's state.
- If the data is static, you could just add it to your component's state when you initialize your component.
Implementation 1:
Add your JSON data in file, for example People.js
:
const peopleData = [
{
"id": 1,
"firstname": "abc",
"lastname": "xyz",
"phone": "+91 789654123",
"email": "abcyz@gmail.com"
},
{
"id": 2,
"firstname": "def",
"lastname": "uvz",
"phone": "+91 123456987",
"email": "defvu@gmail.com"
}
];
export default peopleData;
Then within your component, import it like so:
// myPeopleData will contain your json data
import myPeopleData from '<Relative_Path>/People.js';
For more information about ES6 imports and exports check out this great cheatsheet.
Implementation 2:
- Add a file within your
public
directory containing your JSON data, lets assume it's called people.json
- Within your component, add in the
componentDidMount()
lifecycle method then fetch your data.
- Add your fetched data to your component's state.
Your component might look something along the lines of:
import React, { Component } from "react";
import { Container, Grid, Header, List } from "semantic-ui-react";
class MyComponent extends Component {
state = {
peopleData: []
};
componentDidMount() {
fetch('./people.json')
.then(response => response.json())
.then(data => this.setState({ peopleData: data }));
}
render() {
...
}
}
export default MyComponent;
Lastly, Implementation 3:
Within your component just add your data as part of it's default state:
import React, { Component } from "react";
import { Container, Grid, Header, List } from "semantic-ui-react";
class MyComponent extends Component {
state = {
peopleData: [
{
"id": 1,
"firstname": "abc",
"lastname": "xyz",
"phone": "+91 789654123",
"email": "abcyz@gmail.com"
},
{
"id": 2,
"firstname": "def",
"lastname": "uvz",
"phone": "+91 123456987",
"email": "defvu@gmail.com"
}
]
};
render() {
...
}
}
export default MyComponent;
Regardless of the approach you take to import your JSON data, you will need to map through your resulting array within your render()
method. For more information about Array.protoype.map()
method check out MDN's documentation as well as React's Documentation for mapping through lists and rendering list items. Both of which are fantastic resources.
Hopefully that helps!