Skip to content

Instantly share code, notes, and snippets.

@fukatani
Created July 9, 2021 08:19
Show Gist options
  • Save fukatani/9f6479e8416df933399981e88325d170 to your computer and use it in GitHub Desktop.
Save fukatani/9f6479e8416df933399981e88325d170 to your computer and use it in GitHub Desktop.
remote react bootstrap table example with react hooks and typescript
// inspired with https://gist.github.com/xabikos/fcd6e709f8ae0c11e33b
import { render } from "react-dom";
import { useState, useEffect } from "react";
import { BootstrapTable, TableHeaderColumn } from "react-bootstrap-table";
import _ from "lodash";
const dataTable = _.range(1, 60).map((x: number) => ({
id: x,
name: `Name ${x}`,
surname: `Surname ${x}`
}));
interface Entry {
id: number;
name: string;
surname: string;
}
interface Data {
items: Entry[];
total: number;
}
// Simulates the call to the server to get the data
const fakeDataFetcher = {
fetch(page: number, size: number): Promise<Data> {
return new Promise((resolve, reject) => {
resolve({
items: _.slice(dataTable, (page - 1) * size, (page - 1) * size + size),
total: dataTable.length
});
});
}
};
function DataGrid() {
const [totalSize, setTotalSize] = useState(0);
const [page, setPage] = useState(1);
const [sizePerPage, setSizePerPage] = useState(10);
const [items, setItems] = useState(new Array<Entry>());
function fetchData(page: number, sizePerPage: number) {
fakeDataFetcher.fetch(page, sizePerPage).then((data: Data) => {
setItems(data.items.slice(0, data.total));
setTotalSize(data.total);
setPage(page);
setSizePerPage(sizePerPage);
});
}
useEffect(() => {
fetchData(page, sizePerPage);
}, []);
function handlePageChange(page: number, sizePerPage: number) {
fetchData(page, sizePerPage);
}
function handleSizePerPageChange(sizePerPage: number) {
// When changing the size per page always navigating to the first page
fetchData(1, sizePerPage);
}
const options = {
onPageChange: handlePageChange,
onSizePerPageList: handleSizePerPageChange,
page: page,
sizePerPage: sizePerPage
};
return (
<BootstrapTable
data={items}
options={options}
fetchInfo={{ dataTotalSize: totalSize }}
remote
pagination
striped
hover
condensed
>
<TableHeaderColumn dataField="id" isKey dataAlign="center">
Id
</TableHeaderColumn>
<TableHeaderColumn dataField="name" dataAlign="center">
Name
</TableHeaderColumn>
<TableHeaderColumn dataField="surname" dataAlign="center">
Surname
</TableHeaderColumn>
</BootstrapTable>
);
}
const rootElement = document.getElementById("root");
render(<DataGrid />, rootElement);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment