How can i specific expanded data row in react-table?

Viewed 10986

From this document example.

https://react-table.js.org/#/story/custom-expander-position

Result from document example :

  1. when i click row0 data that expanded under row0 will show Hello
  2. when i click row1 data that expanded under row1 will show Hello

about props SubComponent in ReactTable. when a row is expanded that will show same data every row but I want to show data that specific by rows

Result that I want to do :

  1. when i click row0 data that expanded under row0 will show Hello 0
  2. when i click row1 data that expanded under row1 will show Hello 1

How can I do this with react-table ?

2 Answers

You can try this for you Subcomponent:

SubComponent={(v) => <div style={{padding: '10px'}}>Hello {v.row._index}</div>}

sandbox: https://codesandbox.io/s/o708980o7q

v is the element, and you get the index of the row to display. Hope this helps.

For React table v7.7.0 using hooks, To expand on row click follow below,

Step 1: Pass useExpanded to useTable.

Step 2: For subComponent

  const renderRowSubComponent = React.useCallback(
({ row }) => (
  <div style={{padding: '10px'}}>Hello {v.row.id}</div>
),
[])

Step 3: To make the row to expand add following to your <tr>

    <tbody>
  {rows.map((row, i) => {
        prepareRow(row)
        return (
          // Use a React.Fragment here so the table markup is still valid
          <React.Fragment {...row.getRowProps()}>
             <tr {...row.getRowProps()} onClick={() => { 
              row.toggleRowExpanded(); // toggle row expand
        }} >
              {row.cells.map(cell => {
                return (
                  <td {...cell.getCellProps()}>{cell.render('Cell')}</td>
                )
              })}
            </tr>
            {/*
                If the row is in an expanded state, render a row with a
                column that fills the entire length of the table.
              */}
            {row.isExpanded ? (
              <tr>
                <td colSpan={visibleColumns.length}>
                  {/*
                      Inside it, call our renderRowSubComponent function. In reality,
                      you could pass whatever you want as props to
                      a component like this, including the entire
                      table instance. But for this example, we'll just
                      pass the row
                    */}
                  {renderRowSubComponent({ row })}
                </td>
              </tr>
            ) : null}
          </React.Fragment>
        )
      })}
  </tbody>
Related