I am using react-table (https://react-table.tanstack.com/) to build a table-like component. Amongst various types of columns few of them are intractable. That means based on the interaction the data(provided to the Table) must be updated. As an example, In the attached screenshot you will notice a column with a type checkbox. Now based on the click to the checkbox, data is also supposed to be updated.
As a solution, I am using the useState
hook and passing the data.
and Updating them onClick event to the checkbox.
.
This seems a working solution to me, but I found a plugin documented in react-table documentation that implements basic state management for prepared rows and their cells.https://react-table.tanstack.com/docs/api/useRowState As it does not have any working sample associated, I am unable to figure out how this plugin can be used to resolve my current requirement.
Here is the codepen link for the working sample https://codesandbox.io/s/awesome-hill-vz7to?file=/src/App.js
react-table provides an example called Editable Data. Essentially you provide a custom cell renderer to the columns array and pass an update function to the useTable
hook. Inside the custom cell renderer you have access to this function and call it whenever the data changes.
This is the example edited so that it fits your use case: https://codesandbox.io/s/strange-flower-dkq5x
The relevant changes are:
// Create an editable cell renderer
const CheckBoxCell = ({
value,
row: { index },
column: { id },
updateMyData, // This is a custom function that we supplied to our table instance
}) => {
const onChange = e => {
updateMyData(index, id, !value)
}
return <input type='checkbox' checked={value} onChange={onChange} />
}
useTable
hook. const columns = React.useMemo(
() => [
{
Header: 'Name',
columns: [
{
Header: 'First Name',
accessor: 'firstName',
},
{
Header: 'Last Name',
accessor: 'lastName',
},
],
},
{
Header: 'Info',
columns: [
{
Header: 'Age',
accessor: 'age',
},
{
Header: 'Visits',
accessor: 'visits',
},
{
Header: 'Status (available)',
accessor: 'status',
Cell: CheckBoxCell,
},
{
Header: 'Profile Progress',
accessor: 'progress',
},
],
},
],
[]
)
const newPerson = () => {
const statusChance = Math.random()
return {
firstName: namor.generate({ words: 1, numbers: 0 }),
lastName: namor.generate({ words: 1, numbers: 0 }),
age: Math.floor(Math.random() * 30),
visits: Math.floor(Math.random() * 100),
progress: Math.floor(Math.random() * 100),
status:
statusChance > 0.5 ? true : false,
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With