i am looking to make something like this:
Let's say that i have two arrays:
names: ["Prisma 2 Case", "PP-Bizon", ...]
imgs: ["img1.png", "img2.png", ...]
one with names and one with picture of the item. What i want to make is a table that has an image and the name in one cell.
I hav etried something like this:
<table className="table">
<tbody>
<tr>
{this.state.names.map((data, i) => {
return <th key={i}>{data}</th>;
})}
</tr>
<tr>
{this.state.imgs.map((data, i) => {
return (
<td key={i}>
<img className="style" src={data} alt="" />
</td>
);
})}
</tr>
</tbody>
</table>;
But what it did are two seperate rows. It has to by some loop because the number of owned items isnt always the same.
Thanks for your answers.
I think the easiest way to solve this problem is create one array and each object of this array has a object that consist of name and image field. then use map and show this new array.
arr = [{name:'',image:''}]
You will need only one loop to achieve what you're looking for. Depending on what you're trying to do and your style, you may need to wrap the name with a span.
Note that this will only work if your two arrays have the same length and are sorted equally (i.e first image is for the first name, and so on).
<table className="table">
<tbody>
<tr>
{this.state.names.map((data, i) => {
return (
<td key={i}>
<img className="style" src={this.state.imgs[i]} alt="" />
{data}
</td>
);
})}
</tr>
</tbody>
</table>
I think this is what you need for the project you are doing hope it helps, tip tho its better to make your json data into something like this [{name: "Prisma 2 Case" image: "img1.png"}, {name: "PP-Bizon" image: "img2.png"}, ...]
Please let me know if something went wrong here.
import React from "react";
function Sample() {
const data = [
{
names: ["Prisma 2 Case", "PP-Bizon"],
imgs: ["img1.png", "img2.png"],
},
];
return (
<>
<table>
<thead>
<tr>
<th>ID</th>
<th>Color</th>
</tr>
</thead>
<tbody>
{data.map(({ names, imgs }) => {
return names.map((name, index) => (
<tr key={name}>
<td key={name}>{name}</td>
<td key={name}>{imgs[index]}</td>
</tr>
));
})}
</tbody>
</table>
</>
);
}
export default Sample;