Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

react-table

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.

like image 818
user2218544 Avatar asked Feb 20 '20 12:02

user2218544


People also ask

How do I move a prop to a row in react table?

In order to apply styling to an entire Row. (eg. make the entire row red if value == "Error"), I would do it in your table UI. In your UI you are going to be calling prepareRow(row) and then using the row to render the cells.

How do you get a cell value in react table?

Get Cell Value: We can get the cell/column value of the table by adding the onClick event to the <td> tags.

What are accessor react tables?

React-table needs data in array format and columns also in array format. Columns take at minimum Header and accessor as column definitions. Here Header is the display name given to the column of the table and accessor is the key in the data (used for mapping column to the matching data).


1 Answers

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} />
      );
    },
  }
like image 170
Luke Dunscombe Avatar answered Sep 26 '22 07:09

Luke Dunscombe