react-datables-example
Example for Datatables usage with React and Webpack
This example will mainly focus on how to use Datatables and its extensions in React project instead of diving into the fabulous API.
How to run this example
1 | npm install && npm start |
Open your browser and navigate to http://localhost:8080/static/entry
How to import Datatables ?
1 | import $ from 'jquery'; |
After being imported, you can initialize a table DOM element normally
$(elem).dataTable(options)
or $(elem).DataTable(options)
Is it possible to use DataTable object directly ?
No, because it is deeply coupled with jQuery, it requires jQuery context to intialize the table.
In fact, the DataTable object is imported by default.
1 | import $ from 'jquery'; |
How to import Bootstrap styling ?
1 | import 'bootstrap/dist/css/bootstrap.css'; |
Then, make sure you configure the css-loader
and style-loader
right in webpack.config.js
file.
How to load the i18n/fonts file asynchronously ?
Extend the dataTable.defaults object
1 | $.extend(true, $.fn.dataTable.defaults, { |
Loading i18n files is just like loading icon font files.
1 | { |
How to load extensions ?
Check the extensions list, https://www.npmjs.com/~datatables
To import an extension, normaly it would require two steps as following:
1 | import 'datatables.net-fixedheader'; |
1. Load the extension script, normaly the entry file is defined in package.json main
property ;
2. Load the style for specific front-end framework. For example, bs
means Bootstrap
.
How to use string templates
ES6 template is a good choice
Data:
1 | [ |
Columns:
1 | [ |
How to use React components in cell rendering
Let’s assume we need to use the react-toggle
component in our table.
We have three ways to use it:
Implement render function and use React DOM server’s renderToStaticMarkup method
1 | { |
Implement datatable createdCell function and create multiple React roots
1 | { |
Prepare the HTML markup first and then initialize the Datatable
1 | <tbody> |
A performance test page is written to show the difference between these ways
http://localhost:8080/static/toggle
And here is the performance report with 5000 data in table comparing above three options.
Option | Duration | usedJSHeapSize |
---|---|---|
renderToStaticMarkup | 6384.74ms | 29.75M |
render | 4579.46ms | 103.95M |
markup | 6497.95ms | 189.78M |
Summary:
- If your component is dummy(e.g stateless funtion), use
renderToStaticMarkup
- If your component has state, but has no dependency in its context, use
render
- If your component has state or has dependency in its context (e.g Redux Componet or React Router Links), use
markup
TODO
- work with JSON data
- Lifecycle
- Using React in column rendering
- How to avoid conflicts between them
- Work with react-dom/server