user2218544
user2218544

Reputation: 362

How to pass a custom prop from App to cell for react-table v7?

This is how I render my Table body:

        <tbody {...getTableBodyProps()}>
          {rows.map((row, i) => {
            prepareRow(row);
            return (
              <Row {...row.getRowProps()}>
                {row.cells.map((cell) => {
                  // return <td {...cell.getCellProps()}>{cell.render("Cell")}</td>;
                  return cell.render("Cell");
                })}
              </Row>
            );
          })}
        </tbody>

This is how I setup columns. I created unique components for each cell.

[
  {
    Header: "Main Header",
    Footer: "Foot",
    columns: [
      {
        Header: "Code",
        accessor: "NominalCode",
        Cell: (props) => {
          return <CodeCell>{props.cell.value}</CodeCell>;
        },
        Footer: () => {
          return <FooterTotalCell>Total</FooterTotalCell>;
        }
      },
      {
        Header: "Description",
        accessor: "Description",
        Cell: (props) => {
          return (
            <DescriptionCell country={props.row.values.Currency}>
              {String(props.cell.value)}
            </DescriptionCell>
          );
        },
        Footer: () => {
          return <td />;
        }
      }
]

I want to pass a function as a prop from my main App.jsx file to DescriptionCell component. This function will be used to do some onClick functionality inside DescriptionCell.

How can I do this?

Thanks.

Upvotes: 22

Views: 29753

Answers (2)

Luke Dunscombe
Luke Dunscombe

Reputation: 324

You can also do this on a Cell by Cell basis by passing a props object directly to the render function:

...
  {rows.cells.map(cell => cell.render('Cell', { test: 'this is a test'}))}
...

Then in your columns definition

columns: [
  ...
  {
    Cell: (props) => {
      console.log(props.test) // the value is 'this is a test'
      return (
        <CustomComponent test={props.test} />
      );
    },
  }

Upvotes: 29

Maxime Hilaire
Maxime Hilaire

Reputation: 81

You can do it via using the column prop which is passed to the Cell component:

columns: [
  ...
  {
    Header: "Description",
    accessor: "Description",
    onClick: () => { alert('click!'); },
    Cell: (props) => {
      return (
        <DescriptionCell onClick={props.column.onClick} country={props.row.values.Currency}>
          {String(props.cell.value)}
        </DescriptionCell>
      );
    },
  }

Or if your function might be used by many other cell (like to update your backend) you could pass the function to the main Table component as in this example: https://github.com/tannerlinsley/react-table/blob/master/examples/kitchen-sink-controlled/src/App.js#L622

Upvotes: 8

Related Questions