js-learner
js-learner

Reputation: 517

React can't read JSON local file value inside component

I am trying to read a value from a local json file, I don't get an error but at the same time the value doesn't show when viewing in browser.

I'm using a local json file, but will be swapping for an endpoint later.

Header.js file

import React, { Component } from 'react';
import data from './data/app';

export class Header extends Component { 
    render() {

        return (
          <header class="header">
            <div class="header__container">
                <strong>{ data.title }<strong>
            </div>
           </header>
         );
     }
}
export default Header

app.json file contents

[
    {
        "title": "Document Title",
        "description": "Details about the total number"
     }
]

I am then importing in a page in the app using the

<Header>
<Header />

Upvotes: 0

Views: 97

Answers (1)

AKX
AKX

Reputation: 169407

(1) Be explicit about the extension:

import data from './data/app.json';

(2) If you want to access data.title, the shape of the file must be

    {
        "title": "Document Title",
        "description": "Details about the total number"
    }

or the code must be

data[0].title

etc.

Upvotes: 2

Related Questions