mercredi 9 juin 2021

How to use checkbox inside react-table?

I have difficulties using a controlled checkbox inside react-table cells. The state value seems to be correct, but the checkboxes are never checked.

import React, { useMemo } from "react";
import { useTable } from 'react-table';
import { Checkbox, useCheckboxState } from 'pretty-checkbox-react';

function Test() {
  const checkbox = useCheckboxState({ state: [] });
  const data = [{group: "A", id: 1 }, {group: "B", id: 2}];

  const columns = useMemo(
    () => [
      {
        Header: 'Checkbox',
        accessor: 'id',
        Cell: ({ cell: { value } }) =>
          <Checkbox value={value} {...checkbox}></Checkbox>
      },
      {
        Header: 'Group',
        accessor: 'group',
      }
    ],
    []
  );

  console.log(checkbox.state);

  const {
    getTableProps,
    getTableBodyProps,
    headerGroups,
    rows,
    prepareRow,
  } = useTable({ columns, data })

  return (
    <table {...getTableProps()} style=>
      <thead>
        {headerGroups.map(headerGroup => (
          <tr {...headerGroup.getHeaderGroupProps()}>
            {headerGroup.headers.map(column => (
              <th
                {...column.getHeaderProps()}
              >
                {column.render('Header')}
              </th>
            ))}
          </tr>
        ))}
      </thead>
      <tbody {...getTableBodyProps()}>
        {rows.map(row => {
          prepareRow(row)
          return (
            <tr {...row.getRowProps()}>
              {row.cells.map(cell => {
                return (
                  <td>
                    {cell.render('Cell')}
                  </td>
                )
              })}
            </tr>
          )
        })}
      </tbody>
    </table>
  )
}

export default Test;



Aucun commentaire:

Enregistrer un commentaire