ReactJS DataTable with Sort, Filter and Pagination Example (PART 1)

fixed-data-table home page
fixed-data-table home page

Today we’re going to learn how to create a simple datatable for react using the FixedDataTable module, since it uses Javascript ES6 code you must have at least some basic knowledge about it. To c ompile our ES6 code we’re going to use Babel and Webpack, since our js files will also contain JSX and React code, besides babel-preset-es2015 we are going to need babel-preset-react as well.

So let’s get started, create your project folder and run npm init to create the package.json file, after that we need to add all the dependencies, the following code has everything we need, just copy and paste it in there:

package.json

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
{
  "name": "test",
  "version": "1.0.0",
  "description": "",
  "main": "main.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "",
  "license": "ISC",
  "devDependencies": {
    "babel-core": "^6.3.17",
    "babel-loader": "^6.2.0",
    "babel-preset-es2015": "^6.3.13",
    "babel-preset-react": "^6.3.13",
    "babel-runtime": "^6.3.19",
    "webpack": "^1.12.9"
  },
  "dependencies": {
    "fixed-data-table": "^0.6.0",
    "react": "^0.14.3",
    "react-dom": "^0.14.3"
  }
}

As devDependencies(dependencies we need only for development) we have webpack and some babel modules, and as regular dependencies we’ll only need react and the fixed-data-table module. Now run npm install, it’ll download and install all the dependencies, it may take a while.

The next step is to configure the webpack module, to do that we need to create the webpack.config.js file and add the following code to it:

webpack.config.js

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
"use strict";
 
module.exports = {
  entry: './main.js',
  output: { path: __dirname, filename: 'bundle.js' },
 
  module: {
    loaders: [
      {
        test: /.js?$/,
        loader: 'babel-loader',
        exclude: /node_modules/,
        query: {
          presets: ['es2015', 'react']
        }
      }
    ]
  },
};

In this file I’m just specifying the files webpack should transform (or transpile) and what loaders it should use to do it. As the entry file we have the main.js, and as the output (the transformed file) we have the bundle.js, both files were not created yet. We’re also saying to webpack that babel-loader will be our loader and that it should test and transform every js file in our project, except the ones inside the node_modules folder. Lastly we are defining es2015 and react as our presets.

OK, now we’re ready to write some code, first let’s create the main.js file with the following code:

main.js

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
import React from 'react';
import ReactDOM from 'react-dom';
import {Table, Column, Cell} from 'fixed-data-table';
 
const rows = [{"id":1,"first_name":"William","last_name":"Elliott","email":"welliott0@wisc.edu",
"country":"Argentina","ip_address":"247.180.226.89"},
{"id":2,"first_name":"Carl","last_name":"Ross","email":"cross1@mlb.com",
"country":"South Africa","ip_address":"27.146.70.36"},
{"id":3,"first_name":"Jeremy","last_name":"Scott","email":"jscott2@cbsnews.com",
"country":"Colombia","ip_address":"103.52.74.225"},
 
// more data
];
 
ReactDOM.render(
    <Table
      height={rows.length * 30}
      width={1150}
      rowsCount={rows.length}
      rowHeight={30}
      headerHeight={30}
      rowGetter={function(rowIndex) {return rows[rowIndex]; }}>
 
      <Column dataKey="id" width={50} label="Id" />
      <Column dataKey="first_name" width={200} label="First Name" />
      <Column  dataKey="last_name" width={200} label="Last Name" />
      <Column  dataKey="email" width={400} label="e-mail" />
      <Column  dataKey="country" width={300} label="Country" />
 
    </Table>,
    document.getElementById('example')
);

This code can already gerenate a basic datatable, but without any features yet (sort, filter and pagination). As you can see I’ve used some JSON data to populate the datatable, but feel free to use your own data if you want. Now if you take a look at the code of our actual table component you’ll see that it’s really easy to understand, almost every attribute of the Table tag is responsible for controlling its dimensions, except the rowGetter, which is responsible for saying where each row should get its data. We should focus on the Column tags, which by far are also very simple, besides the attribute width, we have the dataKey and label, the first one is the name of the JSON field that will be displayed in this column, and the second is the text that will appear in the header.

Now let’s create our HTML:

index.html

1
2
3
4
5
6
7
8
9
10
11
12
13
<!doctype html>
<html>
  <head>
    <meta charset="UTF-8">
    <title>React DataTable</title>
    <link href="node_modules/fixed-data-table/dist/fixed-data-table.css" 
          rel="stylesheet">
  </head>
  <body style="font-family:arial;font-size:12px; background:#e1e1e1">
    <div id="example"></div>
    <script src="bundle.js"></script>
  </body>
</html>

This is just a regular html file, I just added the css from the fixed-data-table module and also the bundle.js, which is the compiled version of our main.js, it’s really important that you put the bundle.js at the end of the body, otherwise it won’t be able to render the datatable.

Now just run the command webpack to generate the bundle.js, if everything goes right you can now open your index.html file on your browser, this should be the result:

ReactJS datatable
ReactJS datatable

Perfect!! Now our datatable can already show the data in the browser, the next step is to start adding some features to this table, like pagination, sorting and filtering, but I’ll leave that to the PART 2 of this tutorial.

That’s it for today!! hope you enjoyed, till the next one!!

How to use ES6 (Very Simple Example)

Compiling Javascript ES6 Code with Babel
Compiling Javascript ES6 Code with Babel

This will be a very simple tutorial on how to use, the new and far more sophisticated version of Javascript, the ES6 (or ES2015 if you prefer). Much people say ES6 is the future of Javascript, but as everybody knows, our browsers cannot run code in this format yet. Web developers are already writing Javascript in ES6 format and using transpilers to transform it into ES5 code so the browsers can read it. For those who doesn’t know, a transpiler is kind of a compiler that converts a code written in one programming language to another similar programming language, in our case from ES6 to ES5.

The reason why I decided to make it simple is because I’ve already seen lots of authors writing more complex and long tutorials involving Grunt, Browserify, JSX, and so on. You would probably spend a reasonable amount of time going through these tutorials. As opposed to them, my goal here is to get you writing ES6 code as quickly as possible, without consuming much of your time.

So let’s get started, the first thing we need is a transpiler, for this tutorial I’m going to be using Babel, to install it just run the following command:

1
npm install babel-cli -g

Now, since Babel doesn’t come with any transformations enabled, we need to explicitly tell what kind of transformation to perform, to do that we also have to install ES2015 preset:

1
npm install babel-preset-es2015 -g

Perfect! Now we’re going to need to write some ES6 code to test if Babel is working, copy the following code into a js file:

test.js

1
2
3
4
5
6
7
8
9
10
11
12
13
class MyFirstES6Class {
  constructor(message) {
    this._message = message;
  }
 
  get message() {
    return this.message;
  }
 
}
 
var myClass = new MyFirstES6Class('Hello World!!');
console.log(myClass.message);

Ok, now via terminal just navigate to your folder and run the following command to generate the compiled js:

1
babel --presets es2015 test.js --out-file compiled.js

That’s it!! If you did it right you should now have the compiled.js file containing the transformed code:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { 
throw new TypeError("Cannot call a class as a function"); } }
 
var MyFirstES6Class = (function () {
  function MyFirstES6Class(message) {
    _classCallCheck(this, MyFirstES6Class);
 
    this._message = message;
  }
 
  _createClass(MyFirstES6Class, [{
    key: 'message',
    get: function get() {
      return this.message;
    }
  }]);
 
  return MyFirstES6Class;
})();
 
var myClass = new MyFirstES6Class('Hello World!!');
console.log(myClass.message);