Skip to content
dnd-grid

useDndGridResponsiveLayout

Manage responsive layouts and breakpoint state.

useDndGridResponsiveLayout keeps a layout per breakpoint, generates missing layouts, and returns ready-to-spread props for DndGrid. Use ResponsiveDndGrid for the default responsive component.

Example

import {
  DndGrid,
  type Layout,
  useContainerWidth,
  useDndGridResponsiveLayout,
} from "@dnd-grid/react";
import "@dnd-grid/react/styles.css";

const layouts: Record<string, Layout> = {
  lg: [
    { id: "a", x: 0, y: 0, w: 4, h: 2 },
    { id: "b", x: 4, y: 0, w: 4, h: 2 },
  ],
  md: [
    { id: "a", x: 0, y: 0, w: 6, h: 2 },
    { id: "b", x: 0, y: 2, w: 6, h: 2 },
  ],
};

export function ResponsiveGrid() {
  const { width, containerRef, mounted } = useContainerWidth({
    measureBeforeMount: true,
  });

  const { gridProps, handleLayoutChange, breakpoint } =
    useDndGridResponsiveLayout({
      width,
      layouts,
      gap: { lg: 16, md: 12 },
      containerPadding: 16,
    });

  return (
    <div ref={containerRef}>
      <p>Breakpoint: {breakpoint}</p>
      {mounted && (
        <DndGrid
          width={width}
          {...gridProps}
          onLayoutChange={handleLayoutChange}
        >
          <div key="a">A</div>
          <div key="b">B</div>
        </DndGrid>
      )}
    </div>
  );
}

Options

OptionTypeDescription
widthnumberRequired. Container width in pixels.
breakpointsRecord<Breakpoint, number>Breakpoint map, defaults to lg, md, sm, xs, xxs.
colsRecord<Breakpoint, number>Column count per breakpoint.
layoutsResponsiveLayoutsControlled layouts per breakpoint.
defaultLayoutsResponsiveLayoutsUncontrolled initial layouts.
gapResponsiveSpacingGap per breakpoint (number or spacing object).
containerPadding`ResponsiveSpacingnull`
compactorCompactorCompaction strategy for generated layouts.
missingLayoutStrategy"derive" | "warn" | "error" | "empty"Control how missing breakpoint layouts are handled.
onBreakpointChange(bp, cols) => voidFires when the active breakpoint changes.
onLayoutsChange(layouts) => voidFires when any breakpoint layout changes.
onLayoutChange(layout, layouts) => voidFires when the active layout changes.
onWidthChange(width, gap, cols, padding) => voidFires on width or breakpoint config changes.

Returns

ValueDescription
layoutLayout for the active breakpoint.
layoutsFull breakpoint layout map.
breakpointCurrent breakpoint key.
colsColumn count for the current breakpoint.
gapResolved gap for the current breakpoint.
containerPaddingResolved container padding for the current breakpoint.
gridProps{ layout, cols, gap, containerPadding } to spread onto DndGrid.
setLayoutForBreakpointUpdate a specific breakpoint layout.
setLayoutsReplace all layouts.
handleLayoutChangeHelper for DndGrid's onLayoutChange.
sortedBreakpointsBreakpoints sorted smallest to largest.