Using React to display JSON as a table

One of the most common things you'll do when you are designing user interfaces on the web is turning structured data into something easily viewable, and one of the most common ways to do it is in a table. APIs are designed to be easily parsed by machines. Even though JSON is one of the more human readable formats, it still takes a bit of work in order to turn it into HTML.

Luckily, React has done a lot to make designing UI easier. It takes care of most of the nitty gritty details by making it easy to embed HTML into JavaScript and attach data to it. It gets even easier when you use a library like react-json-table.

class TableData extends React.Component {	
  constructor () {
    super();
    this.state = { data: null };
  }
  
  componentDidMount () {
    this.data().then(data => {
      const self = this;
      this.setState({data: data});
    });
  }
  
  columns () {
    return [
    	{key: 'name', label: 'Name'},
        {key: 'age', label: 'Age'},
        {key: 'color', label: 'Color', cell: (obj, key) => {
            return <span>{ obj[key] }</span>;
        }}
    ];
  }

  data () {
    return new Promise((resolve, reject) => {
      resolve([
        { name: 'Louise', age: 27, color: 'red' },
        { name: 'Margaret', age: 15, color: 'blue'},
        { name: 'Lisa', age:34, color: 'yellow'}
      ]);
   });
  }

  render () {
    if (this.state.data !== null) {
      return <JsonTable rows={this.state.data} columns={this.columns()} />;
    }
    return <div>Loading...</div>;
  }
}

It's hard to beat this implementation if you are just using raw JavaScript or even older libraries like JQuery. A comparable application would be more code, less reusable, and have less encapsulation.