I’m new to React and I’m trying to import a JSON DATA
variable from an external file. I’m getting the following error:
Cannot find module “./customData.json”
Could some one help me? It works if I have my DATA
variable in index.js
but not when it’s in an external JSON file.
JavaScript
x
19
19
1
import React, {Component} from 'react';
2
import ReactDOM from 'react-dom';
3
import customData from './customData.json';
4
import Profile from './components/profile';
5
import Hobbies from './components/hobbies';
6
7
class App extends Component {
8
render() {
9
return (
10
<div>
11
<Profile name={this.props.profileData.name}imgUrl={this.props.profileData.imgURL} />
12
<Hobbies hobbyList={this.props.profileData.hobbyList}/>
13
</div>
14
);
15
}
16
}
17
18
ReactDOM.render(<App profileData={DATA}/>, document.querySelector('.container'));
19
JavaScript
1
20
20
1
import React, {Component} from 'react';
2
3
var Hobbies = React.createClass({
4
render: function(){
5
var hobbies = this.props.hobbyList.map(function(hobby, index){
6
return (<li key={index}>{hobby}</li>);
7
});
8
return (
9
<div>
10
<h5>My hobbies:</h5>
11
<ul>
12
{hobbies}
13
</ul>
14
</div>
15
);
16
}
17
});
18
19
export default Hobbies;
20
JavaScript
1
15
15
1
import React from 'react';
2
3
var Profile = React.createClass({
4
render: function(){
5
return (
6
<div>
7
<h3>{this.props.name}</h3>
8
<img src={this.props.imgUrl} />
9
</div>
10
)
11
}
12
});
13
14
export default Profile
15
JavaScript
1
8
1
var DATA = {
2
name: 'John Smith',
3
imgURL: 'http://lorempixel.com/100/100/',
4
hobbyList: ['coding', 'writing', 'skiing']
5
}
6
7
export default DATA
8
Advertisement
Answer
One nice way (without adding a fake .js extension which is for code not for data and configs) is to use json-loader
module. If you have used create-react-app
to scaffold your project, the module is already included, you just need to import your json:
JavaScript
1
2
1
import Profile from './components/profile';
2
This answer explains more.