ReactJS – How to create a layout having 3 items per row?

import Card from 'src/components/Card'
import { getTotalRow } from './format'

const Main = () => {
  const data = [
    {
      id: 1,
    },
    {
      id: 2,
    },
    {
      id: 3,
    },
    {
      id: 4,
    },
    {
      id: 5,
    },
    {
      id: 6,
    },
    {
      id: 7,
    },
  ]
  const arrRowItems = getTotalRow(data, 3)

  return (
    <>
      <div>
        {arrRowItems.map((rowItems, index) => {
          return (
            <div key={'key-' + index}>
              <div
                style={{
                  display: 'grid',
                  gridTemplateColumns: '1fr 30px 1fr 30px 1fr',
                }}
              >
                {rowItems.map((item, index) => {
                  return (
                    <>
                      <Card />
                      {index !== 2 ? (
                        <div style={{ width: '15 px' }}></div>
                      ) : null}
                    </>
                  )
                })}
              </div>
              {index !== arrRowItems.length - 1 ? (
                <div style={{ marginTop: '30px' }}></div>
              ) : null}
            </div>
          )
        })}
      </div>
    </>
  )
}

export default Main
export const getTotalRow = (data: Array<any>, itemsPerRow: number) => {
  let allRow: any[][] = []
  let rowItems: any[] = []
  let isNewRow: boolean = false
  data.forEach((element, index) => {
    isNewRow = index % itemsPerRow === 0 ? true : false
    if (isNewRow && rowItems.length > 0) {
      // Push
      allRow.push([...rowItems])

      // Reset
      rowItems = []
      rowItems.push({ ...element })
    } else {
      rowItems.push({ ...element })
    }
  })

  if (rowItems.length > 0) {
    allRow.push([...rowItems])
  }

  return allRow
}

// [
//   [{}, {}, {}],
//   [{}, {}, {}],
//   [{}, {}, {}]
// ]

Be the first to comment

Leave a Reply

Your email address will not be published.


*