Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 644
Ahmad Avatar asked Apr 06 '18 10:04

Ahmad


Video Answer


1 Answers

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.

like image 91
Phillip Avatar answered Oct 13 '22 03:10

Phillip