React Table Pagination
step 1:npm i react-table
Paginate.js
step 2:
import React, { useState, useEffect} from 'react';
import {useMemo} from 'react'
import axios from 'axios';
import style from './style/table.css';
//step 1:--
import { useTable,usePagination } from 'react-table';
import {COLUMNS} from './Columns1';
export default function Paginate() {
const [data1, setData1] = useState([]);
const getEmployee = async () => {
const user = await axios.get('https://jsonplaceholder.typicode.com/posts');
console.log(user.data);
setData1(user.data);
const data1=user.data;
};
useEffect(() => { getEmployee(); }, []);
const columns=useMemo(() => COLUMNS, [])
const Tabledata=useMemo(() => [...data1], [data1]);
//console.log(data);
const tableInstance=useTable({ columns:columns, data:Tabledata },usePagination) ;
const {
getTableProps,
// table props from react-table
getTableBodyProps,
// table body props from react-table
headerGroups,
// headerGroups, if your table has groupings
page, //
prepareRow, // Prepare the row (this function needs to be called for each row before getting the row props)}=tableInstance;
//navigator function that pagination gives
//to navigate into the pages
nextPage,
previousPage,
//boolean properties whether
//u can go next or previous
canNextPage,
canPreviousPage,
//how many pages in total
//what page they are viewing
pageOptions,
state
}=tableInstance;
const {pageIndex}=state
return (
<div>
{/* here i will create table...
<img src="https://hub.dummyapis.com/Image?text=BR&height=120&width=120"
alt="new" /> */}
<table {...getTableProps()}>
<thead>
{headerGroups.map(headerGroup => (
<tr {...headerGroup.getHeaderGroupProps()}>
{headerGroup.headers.map(column => (
<th {...column.getHeaderProps()}>{column.render("Header")}</th>
))}
</tr>
))}
</thead>
<tbody {...getTableBodyProps()}>
{page.map((row, i) => {
prepareRow(row);
return (
<tr {...row.getRowProps()}>
{row.cells.map(cell => {
return <td {...cell.getCellProps()}>{cell.render("Cell")}</td>;
})}
</tr>
);
})}
</tbody>
</table>
<div id='footer'>
<span>
Page {' '}
<strong>{pageIndex+1} of {pageOptions.length}</strong>{' '}
</span>
<button onClick={()=>previousPage()}
disabled={!canPreviousPage}
>Previous</button>
<button onClick={()=>nextPage()}
disabled={!canNextPage}
>next</button>
</div>
step 3:
Define column:--
Columns1.js
//step 1:
export const COLUMNS=[
{
Header:'Id',
accessor:'id',//map with api
},
{
Header:'Title',
accessor:'title'
},
{
Header:'Body',
accessor:'body'
},
]
step4:
component/style/table.css
Comments
Post a Comment