MarksCode
MarksCode

Reputation: 8604

React-Table: Get selectedRowIds in parent component

I'm rendering a react-table and need to know which rows are selected in the parent component.

Here is my table component:

const TableComponent = (props) => {
  const { columns, data } = props;
  const {
    getTableProps,
    getTableBodyProps,
    headerGroups,
    rows,
    prepareRow,
    state: { selectedRowIds },
  } = useTable(
    {
      columns,
      data,
    },
    useRowSelect
  );

  return (
    <table {...getTableProps()}>
        <thead>
            {headerGroups.map((headerGroup) => (
            <tr {...headerGroup.getHeaderGroupProps()}>
                {headerGroup.headers.map((column) => (
                <th {...column.getHeaderProps()}>{column.render("Header")}</th>
                ))}
            </tr>
            ))}
        </thead>
        <tbody {...getTableBodyProps()}>
            {rows.slice(0, 10).map((row, i) => {
            prepareRow(row);
            return (
                <tr {...row.getRowProps()}>
                {row.cells.map((cell) => {
                    return (
                    <td {...cell.getCellProps()}>{cell.render("Cell")}</td>
                    );
                })}
                </tr>
            );
            })}
        </tbody>
    </table>
  );
};

And here is the parent:

function App() {
  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",
            accessor: "status",
          },
          {
            Header: "Profile Progress",
            accessor: "progress",
          },
        ],
      },
    ],
    []
  );

  const data = React.useMemo(() => makeData(10, 3), []);

  return (
    <Table columns={columns} data={data} />
  );
}

I need to know the selectedRowIds in the parent component. Does anyone know how I'd get those from the child?

Upvotes: 4

Views: 3150

Answers (1)

Shubham J.
Shubham J.

Reputation: 646

You can expose the method from child component with useImperativeHandleHook imperativehandle.

And with the help of this hook, you can get the selected row ids in the parent component.

useImperativeHandle(ref, () => ({
    getSelectedRows:()=> selectedRowIds 
}),[selectedRowIds]);

And in parent component you have to call the method with ref as parentRef.current.getSelectedRows()

Let me know if it helps.

Upvotes: 5

Related Questions