Griddle

By nathanharper

Tuesday, Mar 10, 2015

Today as part of React Week, I got a chance to play around with Griddle. The day’s main project was a React app that talks to the public iTunes API to load a list of search results into a grid format — a feat that’s remarkably easy using Griddle.

Warning Griddle seems to have some issues with Babel, the transpiler I’ve been using to enable ES6 in my applications. You’ll need to make sure that your Webpack config for Babel either excludes the /node_modules/ directory, or that your JSX loader is using “harmony”.

// webpack.config.js
module.exports = {
  entry: "./app/App.js",
  output: { filename: "public/bundle.js" },
  module: {
    loaders: [
      // choose on of these setups.
      { test: /\.js$/, loader: 'jsx-loader?harmony' },
      {
        test: /\.js$/,
        exclude: '/node_modules/',
        loader: 'babel-loader'
      }
    ]
  }
};

Once that’s sorted out, we set up our JSONP call to iTunes:

handleSubmit (e) {
  e.preventDefault();

  $.ajax({
    type: 'GET',
    url: `https://itunes.apple.com/search?term=${this.state.term}&entity=${this.state.entity}`,
    dataType: 'jsonp',
    success: (response) => {
      this.props.callback(response.results);
      this.setState({ term: '' });
    },
    error (e) {
      console.log(e);
    }
  });
}

…and then fed the data into a Griddle component, which was as easy as this:

React.createClass({
  // some boring state-related stuff up here...

  render () {
    var griddleMeta = [
      {columnName: 'trackName',displayName: 'Name'},
      {columnName: 'artistName',displayName: 'Artist'},
      {columnName: 'primaryGenreName',displayName: 'Genre'},
      {columnName: 'artworkUrl100',displayName: 'Artwork',customComponent: ImageComponent},
      {columnName: 'trackPrice',displayName: 'Price'},
      {columnName: 'kind',displayName: 'Type'},
      {columnName: 'trackViewUrl',displayName: 'Online Link',customComponent: UrlComponent}
    ];

    // this.state.data is the results array we got from the AJAX callback.
    return  (
      <Griddle
        results={this.state.data}
        tableClassName="table"
        columnMetadata={griddleMeta}
        columns={griddleMeta.map((col) => (col.columnName))} />
    );
  }
});

The customComponent option lets you set a custom React component to use — in this case, two very basic components I made for displaying image and anchor tags. And voila! You get all this.

griddle