Grid Pattern

A background grid pattern made with SVGs, fully customizable using Tailwind CSS.

Grid Pattern

Installation

Copy and paste the following code into your project.

import { useId } from "react"
 
import { cn } from "@/lib/utils"
 
interface GridPatternProps {
  width?: any
  height?: any
  x?: any
  y?: any
  squares?: Array<[x: number, y: number]>
  strokeDasharray?: any
  className?: string
  [key: string]: any
}
 
export function GridPattern({
  width = 40,
  height = 40,
  x = -1,
  y = -1,
  strokeDasharray = 0,
  squares,
  className,
  ...props
}: GridPatternProps) {
  const id = useId()
 
  return (
    <svg
      aria-hidden="true"
      className={cn(
        "pointer-events-none absolute inset-0 h-full w-full fill-gray-400/30 stroke-gray-400/30",
        className
      )}
      {...props}
    >
      <defs>
        <pattern
          id={id}
          width={width}
          height={height}
          patternUnits="userSpaceOnUse"
          x={x}
          y={y}
        >
          <path
            d={`M.5 ${height}V.5H${width}`}
            fill="none"
            strokeDasharray={strokeDasharray}
          />
        </pattern>
      </defs>
      <rect width="100%" height="100%" strokeWidth={0} fill={`url(#${id})`} />
      {squares && (
        <svg x={x} y={y} className="overflow-visible">
          {squares.map(([x, y]) => (
            <rect
              strokeWidth="0"
              key={`${x}-${y}`}
              width={width - 1}
              height={height - 1}
              x={x * width + 1}
              y={y * height + 1}
            />
          ))}
        </svg>
      )}
    </svg>
  )
}

Update the import paths to match your project setup.

Examples

Linear Gradient

Grid Pattern

Dashed Stroke

Grid Pattern

Props

GridPattern

PropTypeDescriptionDefault
widthnumberWidth of the pattern40
heightnumberHeight of the pattern40
xnumberX offset of the pattern-1
ynumberY offset of the pattern-1
squaresnumberX Y coordinates of filled squares as 2D array[]
strokeDasharraystringStroke dash array for the pattern0