Forked from xabikos/remote react bootstrap table example
Created
January 28, 2018 22:28
-
-
Save jgardezi/2c2381d82631e14bff492cebca3b84d8 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