React

React is a Javascript library that is widely used for creating reactive web-applications. We publish the datatables.net-react package which provides DataTables for use as a component in React applications.

The documentation here details how to use this component, and how to make use of the DataTables concepts introduced in the other sections of this manual. They still apply, and are needed to have a good understanding of how to get the best out of DataTables.

Installation and importing

Install the datatables.net-react and datatables.net-dt packages using your package manager:

# npm
npm install --save datatables.net-react datatables.net-dt

# yarn
yarn add datatables.net-react datatables.net-dt

To then use DataTables component in your own components, you need to import both it and DataTables core, then assign DataTables core as the library to use in the component like this:

import DataTable from 'datatables.net-react';
import DT from 'datatables.net-dt';

DataTable.use(DT);

This will give you a <DataTable> React component you can use in your components.

Styling

It might seem like an unnecessary extra step to import the datatables.net-dt package - why doesn't datatables.net-react simply have a dependency on that package? DataTables supports a number of different styling frameworks (Bootstrap, Bulma, Foundation, etc), each of which is published as a different package, so what we are doing here is importing DataTables with default styling and then assigning that as the library to be used by the React component.

If you wanted to make use of DataTables' Bootstrap 5 integration you could install the datatables.net-bs5 package and use that:

import DataTable from 'datatables.net-react';
import DT from 'datatables.net-bs5';

DataTable.use(DT);

Note the key use of the postfix -bs5 rather than -dt in the package name to change the styling integration.

Use the download builder to make sure you get the packages you need (and only those packages!).

Extensions

You can also install DataTables extensions from their own npm packages and use them in the standard manner - e.g. for both Select and Responsive you might use:

# npm
npm install --save \
    datatables.net-select-dt \
    datatables.net-responsive-dt

# yarn
yarn add \
    datatables.net-select-dt \
    datatables.net-responsive-dt

Note the use of the -dt postfix for the styling again - this will change based on the styling package you need - again, use the download builder to get the package names you need!

For each extension, you need to import it for it to be registered with DataTables. For example, to use both Select and Responsive:

import DataTable from 'datatables.net-react';
import DT from 'datatables.net-dt';
import 'datatables.net-select-dt';
import 'datatables.net-responsive-dt';

DataTable.use(DT);

Note that you will also need to provide initialisation options for the extensions to enable them in the DataTable (e.g. select and responsive in this case). Please see the Use section below for details on passing configuration options.

The same installation applies to all of the other DataTables extensions. Use the download builder to get a list of the npm packages for the extensions you want.

Use

Once installed and registered in your component you will have a <DataTable> component available for use in your JSX (you can change the name by changing the import statement used above if you prefer something else). It accepts child elements which can be used to describe the table's headers and footers:

<DataTable>
    <thead>
        <tr>
            <th>Name</th>
            <th>Location</th>
        </tr>
    </thead>
</DataTable>

Properties

The <DataTable> component has the following properties that can be assigned for configuration of the DataTable:

  • ajax - Ajax option for DataTables - to load data for the table over Ajax.
  • className - Class name to assign to the table
  • columns - Define the columns array used for DataTables initialisation
  • data - Data array for DataTables. This is optional and if you are using Ajax to load the DataTable this attribute should not be used.
  • options - The DataTables options for the table. Note that this can include columns, data and ajax - if they are provided by one of the properties from above that will override a matching option given here.
  • slots - An object containing slot functions that can be used to display React components inside the DataTable columns. See the React Components section below.
  • on* - Event functions - see the Events section below.

Basic initialisation

The most basic example use of DataTables in a React application is shown below:

import { useState } from 'react';
import DataTable from 'datatables.net-react';
import DT from 'datatables.net-dt';

import './App.css';

DataTable.use(DT);

function App() {
  const [tableData, setTableData] = useState([
    [ 'Tiger Nixon', 'System Architect' ],
    [ 'Garrett Winters', 'Accountant' ],
    // ...
  ]);

  return (
        <DataTable data={tableData} className="display">
            <thead>
                <tr>
                    <th>Name</th>
                    <th>Position</th>
                </tr>
            </thead>
        </DataTable>
    );
}

export default App;

Example: Basic initialisation.

Ajax data

You might wish to load data for the table to display via Ajax rather than using local React data. That can be done with the ajax property directed to the data source's URL:

import DataTable from 'datatables.net-react';
import DT from 'datatables.net-dt';

DataTable.use(DT);

function App() {
    const columns = [
        { data: 'name' },
        { data: 'position' },
        { data: 'office' },
        { data: 'extn' },
        { data: 'start_date' },
        { data: 'salary' },
    ];

    return (
        <DataTable ajax="/data.json" columns={columns} className="display">
            <thead>
                <tr>
                    <th>Name</th>
                    <th>Position</th>
                    <th>Office</th>
                    <th>Extn.</th>
                    <th>Start date</th>
                    <th>Salary</th>
                </tr>
            </thead>
        </DataTable>
    );
}

export default App;

Example: Ajax data example demonstrating how to use objects as the data source to populate the table via the columns.data option.

Events

DataTables emits a large number of events which can be useful to listen for and react to when the events happen. With the DataTables / React component, you can listen for the events using an on* property (where the full name is defined by the event name in camelCase form and prefixed with on):

<DataTable
    ajax="/data.json"
    onXhr={xhrEvent}
    onDraw={drawEvent}
>

This will listen for xhr and draw, calling the functions as given. The events will be given the same arguments as described in the DataTables documentation.

Example: Listening for events.

Extensions

The installation section above showed how to install and register a DataTables extension. Once they have been installed, they can be used in the standard DataTables way, through their initialisation options. In this example we initialise the Select and Responsive extension using the select option:

import DataTable from 'datatables.net-react';
import DT from 'datatables.net-dt';
import 'datatables.nt-responsive-dt';
import 'datatables.net-select-dt';

DataTable.use(DT);

function App() {
  const columns = [
    { data: 'name' },
    { data: 'position' },
    { data: 'office' },
    { data: 'extn' },
    { data: 'start_date' },
    { data: 'salary' },
  ];

    return (
        <DataTable
            ajax="/data.json"
            columns={columns}
            className="display"
            options={{
                responsive: true,
                select: true,
            }}
        >
            <thead>
            <tr>
                <th>Name</th>
                <th>Position</th>
                <th>Office</th>
                <th>Extn.</th>
                <th>Start date</th>
                <th>Salary</th>
            </tr>
            </thead>
        </DataTable>
    );
}

export default App;

For your CSS file you would also import the extensions - e.g.:

@import 'datatables.net-dt';
@import 'datatables.net-responsive-dt';
@import 'datatables.net-select-dt';

Example: Responsive and Select extensions.

Example: Buttons extension for file export which requires the use of two additional functions to assign JSZip and pdfmake.

API

When working with DataTables, you will often want to use its API to unlock its full potential. This is possible through the ref attribute for the datatables.net-react component.

function App() {
    const table = useRef();

    return (
        <DataTable
            ajax="/data.json"
            ref={table}
        >
            <thead>
                <tr>
                    <th>Name</th>
                    <th>Position</th>
                    <th>Office</th>
                    <th>Extn.</th>
                    <th>Start date</th>
                    <th>Salary</th>
                </tr>
            </thead>
        </DataTable>
    );
}

The ref has an object that contains access to the DataTables through the dt() function - e.g.:

console.log(
    table.current.dt().page.info()
);

Example: API access and usage.

Reactive data

One of the most exciting and useful parts of React is how easy it is to update the display based on a component's state. In summary, when you change a state's value the UI will update automatically to reflect the change - however complex that change might be. The datatables.net-react package fully supports Reacts state data and will automatically reflect the changes made to the state.

In the following example we take the classic React tic-tac-toe tutorial and have it display the moves of the game in the DataTable:

Example: Reactive data

This is done by passing the data state (from useState()) as the data property to the React <DataTable> component.

const [tableData, setTableData] = useState([]);

return (
    <DataTable
        className="display"
        data={tableData}
    >
        <thead>
            <tr>
                <th>Move</th>
                <th>Player</th>
                <th>Position</th>
                <th>Time</th>
            </tr>
        </thead>
    </DataTable>
);

As the game progresses the state is updated as we add to the state array:

const nextTableData = tableData.slice();

nextTableData.push({
    move: nextTableData.length + 1,
    player: xIsNext ? 'X' : '0',
    position: idx,
    time: new Date()
});

setTableData(nextTableData);

React Components

You will likely wish to show React components inside a DataTable's cells at some point. To do this, the DataTable component supports the ability to define a "slot" function for each column. This function is passed data about the cell that is being rendered and takes a React element / JSX as a return.

This is done using the slots property for the <DataTable> component. It is an object whose keys are either column indexes or column names (columns.name) - these keys are used to identify which column the slot should apply to. Each slot value is a function that can take two or three parameters.

In the following a <Button> component is rendered into column index 0 (i.e. the first column):

<DataTable
    slots={{
        0: (data, row) => (
            <Button onClick={doClick}>
                Click me!
            </Button>
        )
    }}
>

If a slot function expects two parameters they are:

  1. Cell data
  2. Row data

DataTables will then automatically attempt to extract the ordering and search data from the React element that is returned.

If a slot function expects three parameters they are:

  1. Cell data
  2. Data type (sort, type, filter, display)
  3. Row data

If you are already familiar with DataTables, you might recognise these parameters as those used for rendering functions and orthogonal data. It allows you to return specific data that DataTables use for ordering, search and type detection. The display type expects the React element / JSX in the return.

Tic-tac-toe

As an example of this in action, let's take our reactive data example from above, and say that we want to use the <Square> component to display in the table for each move, rather than the string X / O.

That might look something like this:

<DataTable
    slots={{
        1: (data) => {
            return <Square val={data} />;
        }
    }}
>

Note how JSX is used for the function return based on the data passed into it and 1 is used as the column index identifier for the column to apply this index to.

Example: Displaying a React component in a column