1

I am using react-table and need to create subrows with the data structure below. I have successfully created subrows for each object in the data array. However, each object in the data array contains another array "types."

How would i go about getting each row to list the "type" names as subrows?

My code so far is below:

Table:

import React from 'react';
import ReactTable from 'react-table';

const Table = (props) => {
  const subComponent = row => {
    return (
      <div>
        Names of "types" here respectively for each object in data array
        (no column headers or anything needed)
      </div>
    );
  };

  return (
    <ReactTable data={ props.data }
      columns={ props.columns }
      SubComponent={ subComponent } />
  );
};

export default Table;

Data structure:

const data = [
  {
    id: '12345',
    name: 'sports',
    types: [
      {
        name: 'basketball',
        id: '1'
      },
      {
        name: 'soccer',
        id: '2'

      },
      {
        name: 'baseball',
        id: '3'
      }
    ]
  },
  {
    id: '678910',
    name: 'food',
    types: [
      {
        name: 'pizza',
        id: '4'
      },
      {
        name: 'hamburger',
        id: '5'

      },
      {
        name: 'salad',
        id: '6'
      }
    ]
  }
];
2
  • 2
    This might be of help. codesandbox.io/s/relaxed-frost-kln0o?file=/src/App.js:1716-2034 Commented Jan 18, 2022 at 14:41
  • Hi Bro, I am trying past a week I did not add sub row getting error in react-table, as you said you have successfully added sub row on each array, if you have code please share the link just I can refer Commented Mar 31, 2023 at 20:36

2 Answers 2

4

You can rewrite the getSubRows method on useTable optios. Something like this:

const getSubRows = useCallback((row) => {
  return row.types || [];
}, []);
Sign up to request clarification or add additional context in comments.

1 Comment

Can you please elaborate with an example?
1

Here is a good example on how to do it https://codesandbox.io/s/github/tannerlinsley/react-table/tree/master/archives/v6-examples/react-table-sub-components

From my best guess, your code will look like this:

import React from 'react';
import ReactTable from 'react-table';

const Table = (props) => {
  const subComponent = row => {
    return (
      <div>
        row.Original.types.map((type, idx) => (
           <div>{{type.id}}</div>
           <div>{{type.name}}</div>
        ))
      </div>
    );
  };

  return (
    <ReactTable data={ props.data }
      columns={ props.columns }
      SubComponent={ subComponent } />
  );
};

export default Table;

1 Comment

The link is not working

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.