0

I have data.json file in my react app and I would like to use in my home.js file which have currently internally json values.

Is there any way to call data.json file into my this.state constructor.

class Home extends Component { constructor () { super(); this.state={ data:[ { rank:1, name:'Name one', agency:'agency one', }, { rank:2, name:'Name Two', agency:'agency two', }, { rank:3, name:'Name Three', agency:'agency three', } ] } } render() { return ( <div> { this.state.data.map((value) => <div> <span>{value.rank}</span> <span>{value.name}</span> <span>{value.agency}</span> </div> ) } </div> ); } } export default Home; 
1

3 Answers 3

2

You can import it as a default value then assign it in your state.

import data from "./data.json"; class Home extends Component { constructor () { super(); this.state={ data, } } render() { return ( <div> { this.state.data.map((value) => <div> <span>{value.rank}</span> <span>{value.name}</span> <span>{value.agency}</span> </div> ) } </div> ); } } export default Home; 
Sign up to request clarification or add additional context in comments.

1 Comment

Might have to use the spread operator here, like this.state = { data: [ ... data ] }
0

Let's consider your JSON file temp.json stored in the same directory. Assigning to data state on constructor like

 this.state = { package: require("./temp.json") }; 

Use like usual state. this.state.data[0].rank or map.

Example https://codesandbox.io/s/92qpzoz4rw

1 Comment

Thanks Revansiddh, for reply. As I am absolute beginner in react so somehow not able to manage require method. It seems working once I use package.json as per codesandbox but one I use package: require("./json/data.json") file from my json folder somehow error seems. But for now as per current scenario tweak suggested by devserkan works for me, I will surely 100% try this require method as well. just one query, are you available if I have any doubt related your suggested method.
0

You can try this: 1. $ npm install load-json-file; 2. you can view also load-json-file implementation detail here: https://github.com/sindresorhus/load-json-file

import loadJsonFile from 'load-json-file' class Home extends Component { constructor () { super(); this.state={data:''} componentDidMount(){ loadJsonFile('data.json').then(json => { console.log(json); this.setState={data: json} }); } render() { return ( <div> { this.state.data.map((value) => <div> <span>{value.rank}</span> <span>{value.name}</span> <span>{value.agency}</span> </div> ) } </div> ); } } export default Home; 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.