AutoGrid
Overview
The AutoGrid component automatically determines the number of columns based on the available container width and a defined minimum item width.
It’s ideal for dynamic content, responsive galleries, and layouts where the number of items is unknown.
Preview
- Preview
- Code
Item 1
Item 2
Item 3
Item 4
Item 5
Item 6
import AutoGrid from './components/ui';
function Example() {
return (
<AutoGrid minItemWidth="150px" maxColumns={4} gap="normal" balanced>
<div>Item 1</div>
<div>Item 2</div>
<div>Item 3</div>
<div>Item 4</div>
</AutoGrid>
);
}
Installation
- npm
- yarn
- pnpm
- manual
npx @mindfiredigital/ignix-ui add auto-grid
yarn @mindfiredigital/ignix-ui add auto-grid
pnpm @mindfiredigital/ignix-ui add auto-grid
import React, { ReactNode, CSSProperties } from "react";
type Gap = "none" | "small" | "normal" | "comfortable" | "large" | string;
interface AutoGridProps {
children: ReactNode;
minItemWidth?: string; // e.g. "200px"
maxColumns?: number; // max number of columns
gap?: Gap; // spacing between grid items
balanced?: boolean; // balance row heights
className?: string;
}
const gapMap: Record<Exclude<Gap, string>, string> = {
none: "0",
small: "0.5rem",
normal: "1rem",
comfortable: "1.5rem",
large: "2rem",
};
const AutoGrid: React.FC<AutoGridProps> = ({
children,
minItemWidth = "200px",
maxColumns,
gap = "normal",
balanced = false,
className = "",
}) => {
const computedGap = gapMap[gap as keyof typeof gapMap] || gap;
const style: CSSProperties = {
display: "grid",
gap: computedGap,
gridTemplateColumns: `repeat(auto-fit, minmax(${minItemWidth}, 1fr))`,
alignItems: balanced ? "stretch" : "start",
maxWidth: maxColumns
? `calc(${maxColumns} * ${minItemWidth} + (${maxColumns} - 1) * ${computedGap})`
: "100%",
};
return (
<div style={style} className={`auto-grid mx-auto ${className}`}>
{children}
</div>
);
};
export default AutoGrid;
Variants
- Preview
- Code
Item 1
Item 2
Item 3
Item 4
Item 5
Item 6
<AutoGrid
minItemWidth="200px"
maxColumns={4}
gap="normal"
balanced={false}
>
{items.map((item, i) => (
<div key={i} className="bg-gray-200 p-6 rounded-lg shadow text-center">
Item {i + 1}
</div>
))}
</AutoGrid>
Usage
Responsive Gallery
function Gallery() {
return (
<AutoGrid minItemWidth="200px" maxColumns={6} gap="small" balanced>
{images.map((src, i) => (
<img key={i} src={src} className="rounded shadow" />
))}
</AutoGrid>
);
}
Tags or Categories
function TagList({ tags }) {
return (
<AutoGrid minItemWidth="120px" gap="comfortable">
{tags.map((tag, i) => (
<span key={i} className="px-3 py-1 rounded bg-gray-200">
{tag}
</span>
))}
</AutoGrid>
);
}
Props
Prop | Type | Default | Description |
---|---|---|---|
minItemWidth | string | "200px" | Minimum width of each grid item before wrapping. |
maxColumns | number | Infinity | Maximum number of columns allowed. |
gap | "small" | "normal" | "large" | string | "normal" | Gap between grid items. |
balanced | boolean | false | Ensures balanced column heights (ideal for masonry-like layouts). |