Skip to content

Instantly share code, notes, and snippets.

@hpneo
Created October 28, 2017 17:19
Show Gist options
  • Save hpneo/eb786e9099194c8b27b096811a5fac28 to your computer and use it in GitHub Desktop.
Save hpneo/eb786e9099194c8b27b096811a5fac28 to your computer and use it in GitHub Desktop.
import React from 'react';
import PaginatedTable from './PaginatedTable';
import data from './movies';
const App = () => (
<div>
<PaginatedTable data={data} perPage={5} />
</div>
);
export default App;
import React from 'react';
import Table from './Table';
import Paginator from './Paginator';
export default class PaginatedTable extends React.Component {
constructor(props) {
super(props);
this.state = {
currentPage: 1,
};
}
render() {
const { data, perPage } = this.props;
const filteredData = data.slice(
(this.state.currentPage - 1) * perPage, this.state.currentPage * perPage
);
// page 1
// 0 - 1
// page 2
// 2 - 3
// page 3
// 4 - 5
return (
<div>
<Table data={filteredData} />
<Paginator
total={data.length}
perPage={perPage}
onItemClick={(page) => this.setState({ currentPage: page })} />
</div>
);
}
}
import React from 'react';
const renderPage = (item, index, onItemClick) => (
<li onClick={() => onItemClick(index + 1)} key={item}>{index + 1}</li>
);
const Paginator = (props) => {
const pagesCount = Math.ceil(props.total / props.perPage);
const pages = [];
for (let i = 0; i < pagesCount; i++) {
pages.push(i + 1);
}
return (
<ul>
{pages.map((item, index) => renderPage(item, index, props.onItemClick))}
</ul>
);
};
export default Paginator;
import React from 'react';
const renderCell = (cell, index) => (
<td key={index}>
{cell}
</td>
);
const renderRow = (item, index) => (
<tr key={index}>
{Object.keys(item).map((key) => renderCell(item[key], key))}
</tr>
);
const Table = ({ data }) => (
<table>
<tbody>
{data.map(renderRow)}
</tbody>
</table>
);
export default Table;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment