skip to Main Content

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


  1. Ummm, maybe you still need to add a prop key for each components you want to render, like the code below

    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>
      );
    };
    
    const MemoryContainerCounter = () => {
      return <>
        {[1,2,3,4,5,6].map((num) => <MemoryContainer key={num} memoryZoneNumber={num} />)}
      </>;
    };
    
    Login or Signup to reply.
  2. Your 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:

    const data = [
      {id: 1, name: Zone1},
      {id: 2, name: Zone2},
      {id: 3, name: Zone3},
    ];
    

    All you have to do is store either the API JSON result or the hardcoded data in a state variable:

    const [data, setData] = useState([
      {id: 1, name: Zone1},
      {id: 2, name: Zone2},
      {id: 3, name: Zone3},
    ]);
    

    And then iterate over it like so:

    const MemoryContainerCounter = () => {
      const [data, setData] = useState([
        {id: 1, name: Zone1},
        {id: 2, name: Zone2},
        {id: 3, name: Zone3},
      ]);
      return (
        <>
          {data.map((r) => <MemoryContainer key={r.id} memoryZoneNumber={r.id} />)}
        </>
      );
    };
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search