≡

Data

Once you've got a DataTable displayed on your page, you are going to want to have it display some data - that's the whole point after all! Typically in the DataTables React component you will do this in one of two ways:

  • Ajax loading the data to display
  • Using Reactive data

Ajax data

To load data for the table to display via Ajax, rather than using local React data, use the ajax property of the <DataTable> component. This property maps directly to ajax, and in the most simple case will take a string that points to the URL where the JSON data will be loaded from:

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

DataTable.use(DT);

function App() {
    return (
        <DataTable ajax="/data.json">
            <Column title="Name" data="name" />
            <Column title="Position" data="position" />
            <Column title="Office" data="office" />
            <Column title="Extn." data="extn" />
            <Column title="Start date" data="start_date" />
            <Column title="Salary" data="salary" />
        </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.

As the ajax property maps to ajax, you can also use it in the object form if you wish to have control over the Ajax request (see DataTable.AjaxOptions), for example setting the HTTP verb or adding headers to the request.

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);