1. create sample app table1
npx create-react-app table1
2. verify the sample app
cd table1
npm start
3. add reat-table
npm install react-table
4. we have install the dependancy, now let's create mock values
and create data as needed and save and download.
Create a new folder inside your app 'component'
new data file 'MOCK_DATA.json'
5. create 'column.js' to add column values
// define labels for wach column
export const COLUMNS = [
{
Header: 'Id',
accessor: 'id'
},
{
Header: 'First Name',
accessor:'first_name'
},
{
Header: 'Last Name',
accessor:'last_name'
},
{
Header: 'Date of Birth',
accessor:'date_of_birth'
},
{
Header: 'Country',
accessor:'country'
},
{
Header: 'Phone',
accessor:'phone'
},
]
6. create 'BasicTable.js' to make table
import React, { Component, useMemo } from 'react';
import {useTable} from 'react-table';
import MOCK_DATA from './MOCK_DATA.json';
import COLUMNS from './columns';
class BasicTable extends Component {
const columns = useMemo(() => COLUMNS,[])
const data = useMemo(() => MOCK_DATA,[])
// useTable({
// // columns: COLUMNS,
// // data: MOCK_DATA
// // can rewrite as
// // columns: columns,
// // data: data
// // further we can simplify
// columns,
// data
// })
// next we create a const to store the useTable
const tableInstance useTable({
columns,
data
})
//step6 - render table props
const {
getTableProps,
getTableBodyProps,
headerGroups,
rows,
prepareRow
} = tableInstance
render() {
return (
// step 4 - define table structure
// convert div tag to table tag with <thead> and tbody
// then add <tr> to both thead and tbody to add a row
// in header use <th> and in body use <td> to add values respectively
<table>
<thead>
<tr>
<th></th>
</tr>
</thead>
<tbody>
<tr>
<td></td>
</tr>
</tbody>
</table>
);
}
}
export default BasicTable;
No comments:
Post a Comment