Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version

To assign separate key: value pairs to multiple lines in a row using react-table-v6, you should use the "columns" array to define the columns and their properties. Each object in the "columns" array should have a "Header" property that defines the column header name and a "accessor" property that defines how to retrieve the data for that column from the row data.

Here is an example of how to assign key: value pairs to multiple lines using react-table-v6:

import React from 'react'
import { useTable } from 'react-table'

function Table({ data }) {
  const columns = [
    {
      Header: 'Name',
      accessor: 'name',
    },
    {
      Header: 'Age',
      accessor: 'age',
    },
    {
      Header: 'Address',
      accessor: 'address',
      Cell: ({ value }) => (
        <div>
          {value.street}<br />
          {value.city}, {value.state}<br />
          {value.zip}
        </div>
      ),
    },
  ]

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

  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.map((row, i) => {
          prepareRow(row)
          return (
            <tr {...row.getRowProps()}>
              {row.cells.map(cell => (
                <td {...cell.getCellProps()}>{cell.render('Cell')}</td>
              ))}
            </tr>
          )
        })}
      </tbody>
    </table>
  )
}

export default Table

In this example, we define a "columns" array with three objects, each representing a column in the table. The "Name" and "Age" columns use a simple "accessor" function to retrieve the data for each row. The "Address" column has a custom "Cell" renderer that generates separate lines for the components of the address value.

When we use the "useTable" hook to create the table, we pass in the "columns" array and the "data" array. We then use the various methods from the hook to render the table components by mapping over the "headerGroups" and "rows" arrays.