Forked from xabikos/remote react bootstrap table example
Created
June 3, 2018 22:49
-
-
Save mrlynn/3168d1cc0154f742b3762915e5cbb7f1 to your computer and use it in GitHub Desktop.
An example of a react bootstrap table that fetches the data asynchronously when navigating between pages and when changing the page size
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import React, {Component} from 'react'; | |
import {BootstrapTable, TableHeaderColumn} from 'react-bootstrap-table'; | |
import _ from 'lodash'; | |
const dataTable = _.range(1, 60).map(x => ({id: x, name: `Name ${x}`, surname: `Surname ${x}`})); | |
// Simulates the call to the server to get the data | |
const fakeDataFetcher = { | |
fetch(page, size) { | |
return new Promise((resolve, reject) => { | |
resolve({items: _.slice(dataTable, (page-1)*size, ((page-1)*size) + size), total: dataTable.length}); | |
}); | |
} | |
}; | |
class DataGrid extends Component { | |
constructor(props) { | |
super(props); | |
this.state = { | |
items: [], | |
totalSize: 0, | |
page: 1, | |
sizePerPage: 10, | |
}; | |
this.fetchData = this.fetchData.bind(this); | |
this.handlePageChange = this.handlePageChange.bind(this); | |
this.handleSizePerPageChange = this.handleSizePerPageChange.bind(this); | |
} | |
componentDidMount() { | |
this.fetchData(); | |
} | |
fetchData(page = this.state.page, sizePerPage = this.state.sizePerPage) { | |
fakeDataFetcher.fetch(page, sizePerPage) | |
.then(data => { | |
this.setState({items: data.items, totalSize: data.total, page, sizePerPage}); | |
}); | |
} | |
handlePageChange(page, sizePerPage) { | |
this.fetchData(page, sizePerPage); | |
} | |
handleSizePerPageChange(sizePerPage) { | |
// When changing the size per page always navigating to the first page | |
this.fetchData(1, sizePerPage); | |
} | |
render() { | |
const options = { | |
onPageChange: this.handlePageChange, | |
onSizePerPageList: this.handleSizePerPageChange, | |
page: this.state.page, | |
sizePerPage: this.state.sizePerPage, | |
}; | |
return ( | |
<BootstrapTable | |
data={this.state.items} | |
options={options} | |
fetchInfo={{dataTotalSize: this.state.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> | |
); | |
} | |
} | |
export default DataGrid; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment