Hseleiro Hseleiro - 2 months ago 10
Javascript Question

Import Json File in React

Im new to React and i'm trying to import a json DATA from an external file, im gettin the error

Cannot find module "./customData.json"

Could some one help me ? It work if i have my DATA on my index. but not external

my code index.js

import React, {Component} from 'react';
import ReactDOM from 'react-dom';
import customData from './customData.json';
import Profile from './components/profile';
import Hobbies from './components/hobbies';


class App extends Component {

render() {
return (
<div>
<Profile name={this.props.profileData.name}imgUrl={this.props.profileData.imgURL} />
<Hobbies hobbyList={this.props.profileData.hobbyList}/>
</div>
);
}

}


ReactDOM.render(<App profileData={DATA}/>, document.querySelector('.container'));


hobbies.js

import React, {Component} from 'react';

var Hobbies = React.createClass({
render: function(){
var hobbies = this.props.hobbyList.map(function(hobby, index){
return (<li key={index}>{hobby}</li>);
});

return (
<div>
<h5>My hobbies:</h5>
<ul>
{hobbies}
</ul>
</div>
);
}
});


export default Hobbies;

profile.js

import React from 'react';

var Profile = React.createClass({
render: function(){
return (
<div>
<h3>{this.props.name}</h3>
<img src={this.props.imgUrl} />
</div>
)
}
});

export default Profile


CustomData.Json

var DATA = {

name: 'John Smith',
imgURL: 'http://lorempixel.com/100/100/',
hobbyList: ['coding', 'writing', 'skiing']

}

export default DATA


Thanks in advance !!

Answer

try with export default DATA or module.exports = DATA

Comments