How to display an array of objects row-by-row using React Table?
I want to display movies row-by-row without changing the data model.
Here's my code:
import*asReactfrom"react";import{useTable}from"react-table";constborderStyle={border:"1px dashed navy"};exportdefaultfunctionApp(){constdata=React.useMemo(()=>[{actor:"Johnny Depp",movies:[{name:"Pirates of the Carribean 1"},{name:"Pirates of the Carribean 2"},{name:"Pirates of the Carribean 3"},{name:"Pirates of the Carribean 4"}]}],[]);constcolumns=React.useMemo(()=>[{Header:"Actor",accessor:"actor",},{Header:"Movies",accessor:(row,index)=>{console.log({row});// i want to display this row-by-row instead of in 1-row without changing data model
returnrow.movies.map(movie=>movie.name);}}],[]);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()} style={borderStyle}>{column.render("Header")}
</th>
))}</tr>
))}
</thead><tbody{...getTableBodyProps()}>
{rows.map((row,i)=> {
prepareRow(row);
if(i==0){console.log({row});}return(
<tr{...row.getRowProps()}>
{row.cells.map((cell,j) =>{if(i==0&&j<2){console.log({cell,i,j});}return(
<td{...cell.getCellProps()}style={borderStyle}>{cell.render("Cell")}
</td>
);
})}
</tr>
);
})}
</tbody>
</table>
);
}
It currently looks like:
Here's the direct link to it: https://codesandbox.io/s/modest-sanderson-z0keq?file=/src/App.tsx
My movie list is an array of objects so how will I display it beside actor name? So it looks like:
You basically want to structure your table like this:
<tr>
<td>Johnny Depp</td>
<td>Pirates of the Caribbean 1</td>
</tr>
<tr>
<td>Johnny Depp</td>
<td>Pirates of the Caribbean 2</td>
</tr>
<tr>
<td>Johnny Depp</td>
<td>Pirates of the Caribbean 3</td>
</tr>
<tr>
<td>Johnny Depp</td>
<td>Pirates of the Caribbean 4</td>
</tr>
You're currently doing:
<tr>
<td>Johnny Depp</td>
<td>Pirates of the Caribbean 1
Pirates of the Caribbean 2
Pirates of the Caribbean 3
Pirates of the Caribbean 4
</td>
</tr>
So you'll either have to modify your data or your loop.
View all comments
1
u/deadcoder0904 May 02 '20
How to display an array of objects row-by-row using React Table?
I want to display movies row-by-row without changing the data model.
Here's my code:
It currently looks like:
Here's the direct link to it: https://codesandbox.io/s/modest-sanderson-z0keq?file=/src/App.tsx
My movie list is an array of objects so how will I display it beside actor name? So it looks like: