React - load all data from json into component

Viewed 27723

I am using React and trying to load data into my component from a local json file. I am trying to print all information, including the 'name' in a name:value pair (not just the value) to make it look like a form.

I am looking for the best way to do this. Do I need to parse? Do I need to use a map function? I am new to React so please show me solution with code. I've seen other questions similar to this but they include a lot of other code that I don't think I need.

Example of my code: test.json

{"person": {
  "name": "John",
  "lastname": "Doe",
  "interests":
  [
    "hiking",
    "skiing"
  ],
  "age": 40
}}

test.js

import React, {Component} from 'react';

class Test extends Component {
    render () {
      return (

           ) 
      }
};

export default Test;

I need code that lets me import from json and code inside component that displays ALL fields.

6 Answers
  • After http://localhost:3001/ you type your directory of JSON file: Mydata.json is my JSON file name, you type your file name: Don't forget to import axios on the top. *

componentDidMount() {
    axios.get('http://localhost:3001/../static/data/Mydata.json')
      .then(response => {
      console.log(response.data)
      this.setState({lists: response.data})
    })
 }
 

If you're loading a file over HTTP, then you can use the built-in window.fetch() function (in browsers for the last few years, see Mozilla's developer pages for compatibility support).

fetch("https://api.example.com/items")
  .then(res => res.json())

The React docs explain some other ways of doing Ajax requests (i.e. requests from within an already-loaded web page).

If your JSON is in a local file, then just import it, as others have explained:

import test from 'test.json';
Related