Integrating React and Datatables — not as hard as advertised

Initial Setup

npm i --save-dev datatables.net jquery

Basic UI

Setting up Datatables

const $ = require('jquery');
$.DataTable = require('datatables.net');
const columns = [
{
title: 'Name',
width: 120,
data: 'name'
},
{
title: 'Nickname',
width: 180,
data: 'nickname'
},
];
class Table extends Component { 
componentDidMount() {
$(this.refs.main).DataTable({
dom: '<"data-table-wrapper"t>',
data: this.props.names,
columns,
ordering: false
});
}
componentWillUnmount(){
$('.data-table-wrapper')
.find('table')
.DataTable()
.destroy(true);
}
shouldComponentUpdate() {
return false;
}
render() {
return (
<div>
<table ref="main" />
</div>);
}
}

Updating the table

function reloadTableData(names) {
const table = $('.data-table-wrapper')
.find('table')
.DataTable();
table.clear();
table.rows.add(names);
table.draw();
}
function updateTable(names) {
const table = $('.data-table-wrapper')
.find('table')
.DataTable();
let dataChanged = false;
table.rows().every(function () {
const oldNameData = this.data();
const newNameData = names.find((nameData) => {
return nameData.name === oldNameData.name;
});
if (oldNameData.nickname !== newNameData.nickname) {
dataChanged = true;
this.data(newNameData);
}
return true; // RCA esLint configuration wants us to
// return something
});

if (dataChanged) {
table.draw();
}
}
shouldComponentUpdate(nextProps) {
if (nextProps.names.length !== this.props.names.length) {
reloadTableData(nextProps.names);
} else {
updateTable(nextProps.names);
}
return false;
}

Conclusion

--

--

I am a full stack JavaScript developer at Undertone building complex web application using various front-end and back-end technologies based on Node.js and NPM

Love podcasts or audiobooks? Learn on the go with our new app.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store