简体   繁体   中英

how to display data in table using json in react js?

i have JSON like this

i want to use this JSON and display data in Table using react js.

this is how i display data from JSON file.

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

class App extends Component {
  render() {
    return (
        <ul>
        {
          data.map(function(movie){
            return <li>{movie.id} - {movie.title}</li>;
          })
        }
        </ul>
    );
  }
}

export default App;

how to load JSON from URL and display it in table using reactjs?

You could fetch the JSON once the component will mount, and when you eventually resolve it you can update the state of the component:

import React, { Component } from 'react';


class App extends Component {
  // initially data is empty in state
  state = { data: [] };

  componentDidMount() {
    // when component mounted, start a GET request
    // to specified URL
    fetch(URL_TO_FETCH)
      // when we get a response map the body to json
      .then(response => response.json())
      // and update the state data to said json
      .then(data => this.setState({ data }));
  }


  render() {
    return (
        <ul>
        {
          this.state.data.map(function(movie){
            return <li key={movie.id}>{movie.id} - {movie.title}</li>;
          })
        }
        </ul>
    );
  }
}

export default App;

If you're unable to use fetch , you could use some other libraries like superagent or axios . Or you could even fall back to good ol' XMLHttpRequest .

On another note, when building a list of component it is important they each child have a unique key attribute. I also updated that in the code, with the assumption that movie.id is

Example axios code:

axios.get(URL)
  .then(response => response.data)
  .then(data => this.setState({ data }));

EDIT : as trixn wrote in a reply, componentDidMount is the preferred place to fetch data. Updated code.

EDIT 2 : Added axios code.

You can use axios to send http requests.

It looks like this :

const response = await axios.get(your_url_here);
const items = response.data.items;

About await keyword : How to use await key word on react native?

This is axios GitHub page for the docs : https://github.com/axios/axios

Hope it helps.

You can use the fixed Data table to display the data from the json Response.Since the data is vast and it would be difficult to manage the conventional table, this would be a better alternative.

The documentation is given at

https://github.com/schrodinger/fixed-data-table-2/blob/master/examples/ObjectDataExample.js

This link will help you.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM