Issue
Hi I want to create page to show data and user can insert update in detail page, But i want to create 20 page for display 20 table in my database. So i create table as table component because it easy to reuse table style and function whatever page i need to display. However i don't know how to send row value from my table component. Here my code
MaintainTable.js
export const MaintainTable = ({Columns, Data}) => {
const columns = React.useMemo(() => Columns, [])
const data = React.useMemo(() => Data, [Data])
const [cellValue, setCellValue] = React.useState('')
const getCellValue = (row) =>{
setCellValue(row.value)
}
const tableInstance = useTable({
columns,
data
},useGlobalFilter,useSortBy)
const {
getTableProps,
getTableBodyProps,
headerGroups,
rows,
prepareRow,
state,
setGlobalFilter,
} = tableInstance
const { globalFilter } = state
return (
<>
<GlobalFilter filter={globalFilter} setFilter={setGlobalFilter} />
<Table {...getTableProps()}>
<thead>
{headerGroups.map(headerGroup => (
<tr {...headerGroup.getHeaderGroupProps()}>
{headerGroup.headers.map(column => (
<th {...column.getHeaderProps(column.getSortByToggleProps())}>{column.render('Header')}
<span>
{column.isSorted ? column.isSortedDesc ? ' 🔽 ': ' 🔼 ': ''}
</span>
</th>
))}
</tr>
))}
</thead>
<tbody {...getTableBodyProps()}>
{rows.map((row, i) => {
prepareRow(row)
return (
<tr {...row.getRowProps()} onClick={()=> getCellValue(row)}>
{row.cells.map(cell => {
return <td {...cell.getCellProps()}>{cell.render('Cell')}</td>
})}
</tr>
)
})}
</tbody>
</Table>
</>
)
}
CustomerPage.js
<div className="container">
<div className="row mt-4">
<div className="col-md-12">
<MaintainTable Columns={COLUMNS} Data={customers.data} />
</div>
</div>
</div>
I try using useState to send value but with my code table component must not send value to specific page becuase there are a lot of page using this component. Example i want in my CustomerPage.js if user cilck on table row, I want to show CustomerDeatilPage.js
Solution
If you want to send some data from inner component to parent component you should use callback functions.
Firstly, you create a callback in your CustomerPage and pass it down to your Table components (MaintainTable). Then in MaintainTable you should call this callback on click on row and pass any data you want.
const handleRowClick = (rowName) => {
console.log("This row was clicked:", rowName)
}
...
<div className="container">
<div className="row mt-4">
<div className="col-md-12">
<MaintainTable onRowClick={handleRowClick} Columns={COLUMNS} Data={customers.data} />
</div>
</div>
</div>
And in your MaintainTable
const getCellValue = (row) =>{
props.onRowClick(row.value)
}
Answered By - Oleg Brazhnichenko
Answer Checked By - - Terry (ReactFix Volunteer)