Currently I only get the first value of each object inside itemList:
name | description | details |
---|---|---|
1 | 2 | 3 |
itemList = [
{
id: 1,
name: "item1",
description: "description1",
details: "detail1"
},
{
id: 2,
name: "item2",
description: "description1",
details: "detail2"
},
{
id: 3,
name: "item3",
description: "description1",
details: "detail3"
}
];
function Items() {
const handleRender = () => {
return itemList.map((item) => {
for (let entry in item) {
return (
<div className="grid-item" key={item.id}>
{item[entry]}
</div>
);
}
});
};
return (
<div className="grid-container">
<div className="grid-item">name</div>
<div className="grid-item">description</div>
<div className="grid-item">details</div>
{handleRender()}
</div>
);
}
I tried to loop in different ways, but I either get one div with all the itemList entries as one grid-item, or only the first value of each object.
I want to have three columns:
name | description | details |
---|---|---|
item1 | description1 | details1 |
item2 | description2 | details1 |
item3 | description3 | details1 |
How can I achieve this?
Is it even possible using CSS grid?
4
Answers
You can use HTML table to produce this type of output
For example
We can refactor handleRender
something like this
You can use a single
map
function to display your items. And use the properties to display the ‘cells’.Your css could look something like this.
Instead of a loop, you can use Object.entries to get an array of the properties for a JavaScript object, then outputting the
td
elements for a table is as straightforward as the technique that you already successfully used to.map
its rows.You can also follow the same technique to extract the column names for the header. Just get them from the first row. Note, this doesn’t work for an empty table: with no rows, you won’t get a header. It’s also sensitive to property order, so be careful to normalize your data.
You have omitted the
id
property from your example table, so I’ve used.filter
to remove it here as well.