EN
React - material table with AJAX remote data and pager
3 points
In this article we would like to show you how to create simple application with react material table. On each page change data is fetched with ajax.
The result of this article is visible on below screenshot:
Online runnable example:
To run this app you need to copy 3 files from this article:
- index.js
- index.html
- package.json
Entire application stucture:
Below we can see src code of those 3 files.
index.js
xxxxxxxxxx
1
import React, { forwardRef } from 'react';
2
import ReactDOM from 'react-dom';
3
4
import MaterialTable from "material-table";
5
import ArrowDownward from '@material-ui/icons/ArrowDownward';
6
import ChevronLeft from '@material-ui/icons/ChevronLeft';
7
import ChevronRight from '@material-ui/icons/ChevronRight';
8
import FirstPage from '@material-ui/icons/FirstPage';
9
import LastPage from '@material-ui/icons/LastPage';
10
11
const tableIcons = {
12
FirstPage: forwardRef((props, ref) => <FirstPage {props} ref={ref} />),
13
LastPage: forwardRef((props, ref) => <LastPage {props} ref={ref} />),
14
NextPage: forwardRef((props, ref) => <ChevronRight {props} ref={ref} />),
15
PreviousPage: forwardRef((props, ref) => <ChevronLeft {props} ref={ref} />),
16
SortArrow: forwardRef((props, ref) => <ArrowDownward {props} ref={ref} />),
17
};
18
19
const App = () => {
20
let data = async query => {
21
let url = `https://reqres.in/api/users` +
22
`?per_page=${query.pageSize}` +
23
`&page=${query.page + 1}`;
24
const response = await fetch(url);
25
const result = await response.json();
26
return {
27
data: result.data,
28
page: result.page - 1,
29
totalCount: result.total,
30
};
31
}
32
33
return (
34
<MaterialTable
35
title="Material Table with Ajax, pageable data"
36
icons={tableIcons}
37
options={{
38
search: false,
39
sorting: false
40
}}
41
columns={[
42
{title: 'Id', field: 'id'},
43
{title: 'First Name', field: 'first_name'},
44
{title: 'Last Name', field: 'last_name'},
45
]}
46
data={data}
47
/>
48
)
49
}
50
51
ReactDOM.render(<App />, document.getElementById('root'));
index.html
xxxxxxxxxx
1
2
<html lang="en">
3
<head>
4
<meta charset="utf-8">
5
<title>React App</title>
6
</head>
7
<body>
8
<div id="root"></div>
9
</body>
10
</html>
package.json
xxxxxxxxxx
1
{
2
"name": "react-material-table-with-pager-remote-data-via-ajax",
3
"main": "src/index.js",
4
"dependencies": {
5
"@material-ui/core": "4.11.2",
6
"@material-ui/icons": "4.11.2",
7
"material-table": "1.69.2",
8
"react": "17.0.1",
9
"react-dom": "17.0.1",
10
"react-scripts": "4.0.1"
11
},
12
"scripts": {
13
"start": "react-scripts start",
14
"build": "react-scripts build"
15
},
16
"browserslist": {
17
"production": [
18
">0.2%",
19
"not dead",
20
"not op_mini all"
21
],
22
"development": [
23
"last 1 chrome version",
24
"last 1 firefox version",
25
"last 1 safari version"
26
]
27
}
28
}