import React from "react"; import Box, { BoxProps } from "../box/box"; import { FinalPearlTheme, ResponsiveValue, spacingStyleFunction, } from "../../../theme"; import { useStyleProps } from "../../../hooks"; export type GridProps = BoxProps & { /** * Number of columns in the grid. * * @default 1 */ numCols?: number; /** * The spacing between the grid elements. * * @default 3 */ spacing?: ResponsiveValue; /** The column spacing between the grid elements. */ spacingX?: ResponsiveValue; /** The row spacing between the grid elements. */ spacingY?: ResponsiveValue; }; /** * Grid is a layout component that arranges its children into rows and columns. * Each child is given an equal amount of space. */ const Grid = React.memo( React.forwardRef( ( { children, numCols = 1, spacing = "3", spacingX, spacingY, ...props }: GridProps, ref: any ) => { const computedSpacingStyle = useStyleProps( { paddingHorizontal: spacingX ?? spacing, paddingVertical: spacingY ?? spacing, }, spacingStyleFunction ); const renderRows = () => { const rows: React.ReactElement[][] = []; React.Children.forEach(children, (child, index) => { const rowIndex = Math.floor(index / numCols); if (!rows[rowIndex]) { rows[rowIndex] = []; } rows[rowIndex].push( {child} ); }); return rows.map((row, index) => ( {row} )); }; return ( {renderRows()} ); } ) ); Grid.displayName = "Grid"; export default Grid;