Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

react-table iterating over object array to print values in a column

Tags:

reactjs

I am using react-table to generate tables(https://react-table.js.org/#/story/readme). I have a state defined as following:

this.state = {

    sampleTable:[
        {author: 'Mac', books: [{title:'One', price: 20}, {title:'Two', price: 20}]},
        {author: 'Rick', books: [{title:'Three', price: 20}, {title:'Four', price: 20}]}
    ],

    sampleTableColumns:[
        {Header: 'Author', accessor: 'author'},
        {Header: 'Books', accessor: 'books.title'},
    ],
};

And I am trying to make table as following:

<ReactTable
    className="-highlight"
    data={this.state.sampleTable}
    columns={this.state.sampleTableColumns}
    defaultPageSize={10}
/>

However in the books column I see nothing. I am not sure how am I supposed to iterate over books array so that I can print say book titles in books column?

like image 794
Thinker Avatar asked Jul 31 '17 09:07

Thinker


3 Answers

I had to write my accessor like following:

sampleTableColumns:[
    {
        Header: 'Author',
        accessor: 'author',

    },
    {
        Header: 'Books',
        id:'books',
        accessor: data => {
            let output = [];
            _.map(data.books, book => {
                output.push(book.title);
            });
            return output.join(', ');
        },
    },
],
like image 99
Thinker Avatar answered Nov 15 '22 07:11

Thinker


It's simple without using any dependencies like lodash...

You just need to use React-table Cell attribute

sampleTableColumns:[
{
    Header: 'Author',
    accessor: 'author',
},
{
    Header: 'Books',
    accessor: 'books',
    Cell: (props) => {
        const { sampleTable} = props.original;
        return (
            { sampleTable.books.map( (book) =>(<h4>{book.title}</h4>)) }
        );
    },
},],
like image 44
Shivam Modi Avatar answered Nov 15 '22 06:11

Shivam Modi


I believe Shivam Modi answered it. Using TypeScript his solution could be rendered something like (using built-in row selector):

{
        Header: "Books",
        accessor: "books",
        Cell: ({ row }) => {
            return (
                 row.original.books
                    .map((book: Book) => (
                        <div key={book.id}>
                            <h4>{book.name}</h4>
                        </div>
                    ))
            );
        },
    },
like image 45
nkmuturi Avatar answered Nov 15 '22 08:11

nkmuturi