im trying to output this multiple times,
<div className=mem-container mem-container-1>
<h2>zone-1</h2>
<p>*timestamp* memory stick added</p>
<p>*timestamp* memory stick removed</p>
<p>*timestamp* memory stick added</p>
<h4>zone-1 memory sticks total : 10</h4>
</div>
came up with the idea of,
const MemoryContainer = (memoryZoneNumber) => {
const memContainerClass = `mem-container mem-container-${memoryZoneNumber}`;
return (
<div className={memContainerClass}>
<h2>zone-{memoryZoneNumber}</h2>
<p>*timestamp* memory stick added</p>
<p>*timestamp* memory stick removed</p>
<p>*timestamp* memory stick added</p>
<h4>zone-{memoryZoneNumber} memory sticks total : 10</h4>
</div>
);
};
then i do this to output it multiple times,
const MemoryContainerCounter = () => {
const memoryCounterArray = [];
for (let i = 1; i <= 6; i++) {
memoryCounterArray.push(MemoryContainer(i));
}
return memoryCounterArray;
};
is this the right approach in react? or should i use props?
2
Answers
Ummm, maybe you still need to add a prop
key
for each components you want to render, like the code belowYour data should originate from either an API or from a hardcoded array of objects.
In both cases, you are dealing with an array of objects.
For example:
All you have to do is store either the API JSON result or the hardcoded data in a state variable:
And then iterate over it like so: