Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React - load all data from json into component

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.

like image 265
ChloeH Avatar asked Jul 10 '17 18:07

ChloeH


People also ask

How do you pass JSON values into React components?

To summarize, you can pass JSON data to other components using props or an event bus; which method to choose is for you to decide based on the requirements of your app. However, it is advised that you use props so that React can keep track of the data and communication between the components.

How use JSON file data in React?

Create a local JSON file named data. json in the public directory of a blank Create React App project. Your React component's Fetch API requests always look for files or other relevant assets in this public directory.


1 Answers

If your json is stored locally, you don't have to use any library to get it. Just import it.

import React, {Component} from 'react';
import test from 'test.json';

class Test extends Component {
  render () {
    const elem = test.person;
    return (
     <ul>
       {Object.keys(elem).map((v, i) => <li key={i}>{v} {test[v]}</li> )}
     </ul>
    )
  }
};

export default Test;
like image 199
kind user Avatar answered Oct 17 '22 06:10

kind user