Search code examples
javascriptreactjsreact-nativeobjectjsx

Render list of arrays inside an object into divs with up to four items in React


I have an object like this:

export const dataEstrenos = [
    {
      id: 1, product: "any product", title: "any title"
    },
    {
      id: 2, product: "any product", title: "any title"
    },
    {
      id: 3, product: "any product", title: "any title"
    },
    {
      id: 4, product: "any product", title: "any title"
    },
    {
      id: 5, product: "any product", title: "any title"
    },
    {
      id: 6, product: "any product", title: "any title"
    },
    {
      id: 7, product: "any product", title: "any title"
    }  
  ];

I want to display items in groups of four elements inside a container div, like this:

<div>
    <div>Here data from first item</div>      
    <div>Here data from second item</div>      
    <div>Here data from third item</div>      
    <div>Here data from fourth item</div> 
</div>
<div>      
    <div>Here data from fifth item</div>      
    <div>Here data from sixth item</div>     
    <div>Here data from seventh item</div>
</div>

...Items inside object may be any quantity, and the last container div may not have four items depending on how many items are left in the array/object (like the example above).

How can I achieve this in react? I am new to React so my attempts to achieve this are not worth showing here. Thank you!


Solution

  • I would first split the array in to sub arrays. If you have a favorite utility library it probably has a function for this, such as Lodash's chunk, or Ramda's splitEvery. Or you could write your own.

    const createChunks = (array, size) => {
      const chunks = [];
      for (let i = 0; i < array.length; i += size) {
        chunks.push(array.slice(i, i + size));
      }
      return chunks
    }
    
    // In your component:
    const chunks = createChunks(dataEstrenos, 4);
    

    After that, map over the arrays like this:

    return (
      <>
        {chunks.map((chunk, i) => (
          <div key={i}>
            {chunk.map((item) => (
              <div key={item.id}>Here data from item. Eg, {item.title}</div>
            ))}
          </div>
        ))}
      </>
    );