My FeedDiscussionsHeadless CMS
New
Sign in
Log inSign up
Learn more about Hashnode Headless CMSHashnode Headless CMS
Collaborate seamlessly with Hashnode Headless CMS for Enterprise.
Upgrade ✨Learn more

Using a local .json file in React

Marvin Dick's photo
Marvin Dick
·Feb 15, 2018

Hey, I'm looking at this codepen: codepen.io/chriscoyier/pen/jqyWXo to learn how to work with data I get from json files in React. My attempt looks as follows:

//index.js
import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import registerServiceWorker from './registerServiceWorker';

import {NavBar} from './NavBar/navbar';
import {Concert} from './Concert/concert';


ReactDOM.render(<NavBar />, document.getElementById('navbar'));
ReactDOM.render(<Concert source="./concerts.json" />, document.getElementById('concert'));
registerServiceWorker();
//concert.js
import React from 'react';
import './concert.css';

var axios = require('axios');

export class Concert extends React.Component {

    getInitialState() {
    return {
        concerts: []
    }
}

    componentDidMount() {
    var th = this;
    this.serverRequest =
        axios.get(this.props.source)
            .then(function(result) {
                th.setState({
                    concerts: result.data.concerts
                });
            })
}

    componentWillUnmount() {
    this.serverRequest.abort();
}

    render(){
        return (
            <div>
                <h1>Concerts!</h1>
                {this.state.concerts.map(function(concert) {
                    return (
                        <div key={concert.id} className="concert">
                            <a href="placeholder.asp">
                                {concert.name}
                                has a price of
                                {concert.price}
                            </a>
                        </div>
                    );
                })}
            </div>
        )

    }

}

Which doesn't seem to work, React throws me an " TypeError: Cannot read property 'concerts' of null " with reference to:

//here in index.js
ReactDOM.render(<Concert source="./concerts.json" />, document.getElementById('concert'));
//here in concert.js
{this.state.concerts.map(function(concert) {

The 'concerts.json' file is located in the /src folder as index.js is.