New:Socket for Asana Is Now Available.Learn more
Get Started

masonry-snap-grid-layout

Package Overview
Dependencies
Maintainers
1
Versions
36
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

masonry-snap-grid-layout

Masonry grid layout for React, Vue 3, Angular, and Vanilla JS. Pinterest-style responsive image gallery with scroll virtualization, SSR support for Next.js and Nuxt, automatic relayout on image load, and responsive column breakpoints. Zero dependencies, T

latest
Source
npmnpm
Version
1.3.0
Version published
Weekly downloads
36
-85.43%
Maintainers
1
Weekly downloads
 
Created
Source

masonry-snap-grid-layout

Masonry grid layout for React, Vue 3, Angular, and Vanilla JS.

Pinterest-style responsive image galleries with scroll virtualization and SSR. One framework-agnostic layout core. Four adapters. Zero dependencies.

A six-column masonry grid of items with varying heights, each placed in the shortest available column

npm version npm downloads jsDelivr hits minzipped size

CI Zero dependencies TypeScript Socket License: MIT


Try it

Vanilla JS Sandbox React Sandbox Vue 3 Sandbox

Run the examples locally

Overview

masonry-snap-grid-layout is a zero-dependency, TypeScript-first masonry layout engine for building Pinterest-style grids and responsive image galleries. It ships first-class components for React, Vue 3, and Angular, plus a plain Vanilla JS class — all driven by the same core, so every adapter produces identical placement.

It uses native CSS masonry where a browser supports it and falls back to a fast JS engine everywhere else, with no configuration either way. Items are placed by a shortest-column-first algorithm:

┌──────────┐  ┌──────────────┐  ┌─────────┐
│  Card 1  │  │   Card 2     │  │ Card 3  │
└──────────┘  │   (tall)     │  └─────────┘
┌───────────┐ │              │  ┌─────────────┐
│  Card 4   │ └──────────────┘  │   Card 5    │
│  (tall)   │ ┌──────────┐      │             │
└───────────┘ │  Card 6  │      └─────────────┘
              └──────────┘

The layout is self-healing. Images decoding, web fonts swapping, and embeds resizing each trigger an automatic relayout, so you never hit the classic masonry failure of items overlapping because they were measured before their content settled — no imagesLoaded-style helper required.

It also handles the parts most masonry libraries leave to you: scroll virtualization for very large lists (against the page or any scrollable panel), responsive column breakpoints, server-side rendering for Next.js and Nuxt, and keyed reconciliation so reordering or filtering a list does not scramble it.

Table of Contents

Why this library

  • One engine, four frameworks. The layout algorithm is not reimplemented per adapter, so React, Vue, Angular, and Vanilla produce byte-identical placement.
  • Images actually work. Per-item observation means a gallery lays out correctly even though heights are unknown at first paint. Most masonry libraries require you to wire up an imagesLoaded-style helper yourself.
  • Virtualization that fits real apps. Virtualize against the page or any overflow: auto panel, modal, or dashboard pane — and skip the initial full mount entirely with estimatedItemHeight.
  • SSR-first. Items are present in the server-rendered HTML, so they are crawlable and painted before hydration.
  • Small and dependency-free. Roughly 5 kB gzipped including shared chunks, with a size budget enforced in CI.
  • Verified across every adapter. 251 tests covering Vanilla, React, Vue, and Angular, plus three separate typecheck passes — including a suite that renders in pure Node with no window, testing the real SSR path rather than a jsdom imitation.

Features

CategoryFeatureDetail
Self-healingImages & async contentRelayouts when images decode, fonts swap, or embeds resize
ColumnsExplicit & responsiveFixed columns, or a mobile-first map like { 0: 1, 640: 2, 1024: 3 }
VirtualizationPage or scroll containerVirtualize against the window or any overflow: auto element
Large listsEstimated heightsestimatedItemHeight skips the render-everything measurement pass
CSS-firstNative CSS masonryUses grid-template-rows: masonry when the browser supports it
JS engineUniversal fallbackAbsolute-position layout works in every browser today
SSRServer-side renderingItems in the page source — crawlable, painted before hydration
Item identityKeyed reconciliationgetItemKey reuses DOM nodes across reorders, filters, and prepends
PerformanceFrame-coalescedScroll, resize, and image events collapse into one layout per frame
ResponsiveResizeObserverRecalculates columns automatically on container resize
AnimationsSmooth transitionsGPU-composited CSS transform transitions on layout changes
TypeScriptFully typedGeneric <T> for your data, typed props, slots, and events
Zero depsNo dependenciesNothing to audit, nothing to update
FrameworksMulti-frameworkVanilla JS · React · Vue 3 · Angular

Installation

npm install masonry-snap-grid-layout
yarn add masonry-snap-grid-layout
pnpm add masonry-snap-grid-layout
bun add masonry-snap-grid-layout

The stylesheet is required in every framework:

import 'masonry-snap-grid-layout/style.css';

Or via CDN:

<link
  rel="stylesheet"
  href="https://cdn.jsdelivr.net/npm/masonry-snap-grid-layout/dist/style.css"
/>

React, Vue, and Angular are optional peer dependencies — install only the one you use. Nothing from the other frameworks is included in your bundle.

Quick Start

Vanilla JS

import MasonrySnapGridLayout from 'masonry-snap-grid-layout';
import 'masonry-snap-grid-layout/style.css';

const masonry = new MasonrySnapGridLayout(document.getElementById('grid'), {
  items,
  gutter: 16,
  minColWidth: 240,
  getItemKey: (item) => item.id, // enables DOM reuse across updates
  renderItem: (item, index) => {
    const el = document.createElement('div');
    el.style.height = `${item.height}px`;
    el.textContent = `${index}. ${item.title}`;
    return el;
  },
});

masonry.updateItems(newItems); // swap the data
masonry.setOptions({ gutter: 24 }); // change options in place
masonry.refresh(); // force a layout pass
masonry.destroy(); // remove styles, stop all observers

React

SSR-safe — works with Next.js (App and Pages Router), Remix, and plain Vite.

import MasonrySnapGrid from 'masonry-snap-grid-layout/react';
import 'masonry-snap-grid-layout/style.css';

export default function Gallery({ items }) {
  return (
    <MasonrySnapGrid
      items={items}
      columns={{ 0: 1, 640: 2, 1024: 3 }}
      gutter={16}
      getItemKey={(item) => item.id}
      virtualize
      overscan={300}
      renderItem={(item) => (
        <article style={{ borderRadius: 12, overflow: 'hidden' }}>
          <img src={item.src} alt={item.alt} style={{ width: '100%' }} />
          <h3>{item.title}</h3>
        </article>
      )}
    />
  );
}

Images need no extra wiring — the grid relayouts as each one decodes.

Vue 3

Drop-in component with a typed scoped slot.

<script setup lang="ts">
import MasonrySnapGrid from 'masonry-snap-grid-layout/vue';
import 'masonry-snap-grid-layout/style.css';

const items = [/* ... */];
</script>

<template>
  <MasonrySnapGrid
    :items="items"
    :columns="{ 0: 1, 640: 2, 1024: 3 }"
    :gutter="16"
    :get-item-key="(item) => item.id"
    :virtualize="true"
    :overscan="300"
    @layout="(info) => console.log(info.columnCount)"
  >
    <template #default="{ item, index }">
      <article :style="{ borderRadius: '12px' }">
        <img :src="item.src" :alt="item.alt" style="width: 100%" />
        <h3>{{ index }}. {{ item.title }}</h3>
      </article>
    </template>
  </MasonrySnapGrid>
</template>

Angular

A standalone component ships with the package, for Angular 17+.

import { Component } from '@angular/core';
import { MasonrySnapGridComponent } from 'masonry-snap-grid-layout/angular';
import type { LayoutInfo } from 'masonry-snap-grid-layout';

interface Card {
  id: number;
  title: string;
  height: number;
}

@Component({
  selector: 'app-gallery',
  standalone: true,
  imports: [MasonrySnapGridComponent],
  template: `
    <masonry-snap-grid
      [items]="items"
      [gutter]="16"
      [minColWidth]="240"
      [columns]="{ 0: 1, 640: 2, 1024: 3 }"
      [getItemKey]="trackById"
      [renderItem]="renderCard"
      (layout)="onLayout($event)"
    />
  `,
})
export class GalleryComponent {
  items: Card[] = [/* ... */];

  trackById = (card: Card): number => card.id;

  // renderItem returns a DOM element, so it is defined as a class field
  // rather than a method — `this` must stay bound.
  renderCard = (card: Card, index: number): HTMLElement => {
    const el = document.createElement('div');
    el.style.height = `${card.height}px`;
    el.textContent = `${index}. ${card.title}`;
    return el;
  };

  onLayout(info: LayoutInfo): void {
    console.log(`${info.columnCount} columns`);
  }
}

Import the stylesheet once in src/styles.css:

@import 'masonry-snap-grid-layout/style.css';

Two Angular caveats. renderItem returns an HTMLElement, so Angular templates and directives cannot be used for item content — build the element imperatively, or drive the engine directly (below) and project your own template. Virtualization is not available in Angular; use React or Vue if you need it.

Using the engine directly instead of the component
import {
  Component,
  AfterViewInit,
  OnDestroy,
  ViewChild,
  ElementRef,
} from '@angular/core';
import MasonrySnapGridLayout from 'masonry-snap-grid-layout';

@Component({
  selector: 'app-root',
  standalone: true,
  template: `<div #grid></div>`,
})
export class AppComponent implements AfterViewInit, OnDestroy {
  @ViewChild('grid') gridRef!: ElementRef<HTMLDivElement>;
  private masonry?: MasonrySnapGridLayout<Card>;

  ngAfterViewInit(): void {
    this.masonry = new MasonrySnapGridLayout<Card>(this.gridRef.nativeElement, {
      items: this.items,
      gutter: 16,
      renderItem: (item) => {
        const el = document.createElement('div');
        el.textContent = item.title;
        return el;
      },
    });
  }

  ngOnDestroy(): void {
    this.masonry?.destroy();
  }
}

API Reference

Core options

Shared by the Vanilla engine and every adapter. Only items and renderItem are required.

OptionTypeDefaultDescription
itemsT[]requiredArray of data items to render.
renderItem(item: T, index: number) => HTMLElementrequiredReturns the DOM element for each item. React and Vue use JSX/slots instead.
layoutMode'auto' | 'js''auto''auto' uses native CSS masonry when supported, else JS. 'js' always uses JS.
gutternumber16Gap between items, in pixels.
minColWidthnumber250Minimum column width, in pixels. Determines the column count.
columnsnumber | Record<number, number>Fixed column count, or a breakpoint map. Overrides minColWidth. Details
animatebooleantrueSmooth CSS transform transitions on layout changes.
transitionDurationnumber400Transition length in ms (JS mode only).
observeItemResizebooleantrueRelayout when an item's own size changes. Details
watchImagesbooleantrueAlso listen for load / error on images inside items.
estimatedItemHeightnumberHeight assumed before measurement. Details
getItemKey(item: T, index: number) => string | numberStable item identity. Details
onLayout(info: LayoutInfo) => voidCalled after each layout pass.

Vanilla JS methods

masonry.updateItems(items: T[])       // Swap items and re-layout
masonry.setOptions(partialOptions)    // Change any option in place, including layoutMode
masonry.refresh()                     // Force a layout pass
masonry.destroy()                     // Remove layout styles, stop all observers

refresh() is rarely needed — item resizes, image loads, and container resizes are all detected automatically. Reach for it only after mutating item content directly.

React props

All core options apply, plus:

PropTypeDefaultDescription
renderItem(item: T, index: number) => ReactNoderequiredJSX render function (returns React elements, not HTMLElement).
virtualizebooleanfalseOnly render items in or near the viewport.
overscannumber300Extra pixels above and below the viewport to keep rendered.
scrollContainerHTMLElement | RefObject | Window | () => …windowScrolling viewport to virtualize against. Details
getItemKey(item: T, index: number) => React.KeyindexStable React key.
classNamestringExtra CSS class on the container.
styleCSSPropertiesExtra inline styles on the container.

Vue props, slots, and events

Core options apply as kebab-case props (:gutter, :min-col-width, :columns), plus:

PropTypeDefaultDescription
virtualizebooleanfalseOnly render items in or near the viewport.
overscannumber300Extra pixels to keep rendered.
scroll-containerHTMLElement | Window | () => …windowScrolling viewport to virtualize against.
get-item-key(item: T, i: number) => keyindexStable :key.
SlotSlot propsDescription
#default{ item: T, index: number }Template for each card.
EventPayloadDescription
layoutLayoutInfoEmitted after each layout pass.

Exposed via template ref: refresh() forces a layout pass.

Angular inputs and outputs

Selector: masonry-snap-grid. Import MasonrySnapGridComponent from masonry-snap-grid-layout/angular.

MemberKindNotes
Core options@InputEvery option in the core table is available as an input.
layout@OutputEmits LayoutInfo after each layout pass.
refresh()methodForce a layout pass.

Virtualization is not available in Angular.

Types

import type {
  MasonryOptions,
  LayoutMode, // 'auto' | 'js'
  LayoutInfo,
  ColumnsOption, // number | Record<number, number>
  ItemPosition, // { x, y, width }
} from 'masonry-snap-grid-layout';

interface LayoutInfo {
  columnCount: number;
  columnWidth: number;
  containerHeight: number;
  itemCount: number;
  engine: 'css' | 'js';
}

Layout Modes

ModeWhen to useBrowser support
'auto' (default)Always — picks the best available engine automaticallyAll browsers
'js'When you need identical behaviour everywhere, or force JS layoutAll browsers

'auto' detects support at runtime via CSS.supports('grid-template-rows', 'masonry'), so it can never apply the property to a browser that does not implement it.

Native CSS masonry is still experimental and unshipped by default — Firefox has it behind a flag, Chromium has trialled it behind a flag, and the specification itself is unsettled (grid-template-rows: masonry versus the competing display: masonry proposal). In practice almost every visitor gets the JS engine today. Because the check happens at runtime, 'auto' will start using the native path if and when a browser ships it.

Important: 'auto' changes engine based on the visitor's browser, and the CSS engine supports neither virtualization nor transform animations. If you depend on either, set layoutMode="js" explicitly so behaviour is identical everywhere.

Columns and Breakpoints

By default the column count is derived from minColWidth — as many columns of at least that width as will fit. For exact control, use columns.

// A fixed number of columns, regardless of container width
<MasonrySnapGrid items={items} columns={3} renderItem={...} />

// Mobile-first breakpoint map: minimum container width -> column count
<MasonrySnapGrid
  items={items}
  columns={{ 0: 1, 640: 2, 1024: 3, 1440: 4 }}
  renderItem={...}
/>

Breakpoint keys are minimum container widths, so they read exactly like a min-width media query: one column until 640px, two from 640px, three from 1024px. The widest key at or below the current width wins, and keys are compared numerically so declaration order does not matter.

Two details worth knowing:

  • Breakpoints track the container, not the viewport — a grid inside a sidebar responds to the sidebar's width.
  • columns overrides minColWidth. An unusable value (0, negative, NaN, an empty map) falls back to the minColWidth calculation rather than producing a broken grid.

Images and Async Content

Masonry has to measure item heights to place them, but images, web fonts, and embeds all settle after that first measurement. A grid measured against undecoded images is laid out with the wrong heights.

This is handled for you. Every item is watched with its own ResizeObserver, and images inside items get load / error listeners, so the grid relayouts as content settles:

// Nothing to configure — images just work.
<MasonrySnapGrid
  items={photos}
  renderItem={(photo) => <img src={photo.src} alt={photo.alt} />}
/>

Every trigger — 200 images finishing at once, a font swap, a container resize — is coalesced into one layout pass per animation frame, so a burst costs a single relayout rather than one per event.

Opt out if your items are fixed-height and you want to skip the observers entirely:

<MasonrySnapGrid observeItemResize={false} watchImages={false} ... />

Tip: setting width / height or aspect-ratio on your images still helps. It gives the browser a correct box before the image decodes, avoiding the visible reflow that self-healing would otherwise have to correct.

Virtualization

For large lists, enable virtualization so only the visible portion of the grid is in the DOM.

// React
<MasonrySnapGrid items={items} virtualize overscan={300} renderItem={...} />
<!-- Vue -->
<MasonrySnapGrid :items="items" :virtualize="true" :overscan="300">

How it works:

  • Heights are measured and cached.
  • Only items within viewport height + overscan stay in the DOM.
  • The container height is computed from all items, so the scrollbar stays correct.
  • Cached heights position off-screen items, so nothing shifts as you scroll.

Scroll and resize events are coalesced into at most one update per animation frame, and the container's offset is re-read each frame — so a sticky header collapsing mid-scroll cannot desynchronise the visible window.

In a scroll container

By default virtualization tracks the page. To virtualize inside an overflow: auto panel, modal, or dashboard pane, point it at the element:

function Panel({ items }) {
  const scrollRef = useRef<HTMLDivElement>(null);

  return (
    <div ref={scrollRef} style={{ height: 600, overflow: 'auto' }}>
      <MasonrySnapGrid
        items={items}
        virtualize
        scrollContainer={scrollRef}
        renderItem={...}
      />
    </div>
  );
}
<!-- Vue: pass the element itself -->
<div ref="box" style="height: 600px; overflow: auto">
  <MasonrySnapGrid :items="items" :virtualize="true" :scroll-container="box" />
</div>

scrollContainer accepts an element, a React ref, a getter function, window, or 'window'. Memoize getter functions — a new identity resubscribes the listeners.

Very large lists

By default virtualization must mount every item once to learn its height, which defeats the purpose for tens of thousands of items. Supply estimatedItemHeight and positions are estimated up front, so the very first render is already clipped:

<MasonrySnapGrid
  items={items} // 50,000 items
  virtualize
  estimatedItemHeight={240}
  renderItem={...}
/>

Real measurements replace the estimate as items scroll through. A rough estimate is fine — an inaccurate one only means the scrollbar length adjusts as you scroll.

Virtualization is JS-mode only. CSS masonry mode always renders every item, since the browser handles placement natively.

Item Identity

By default items are keyed by array index. That is fine for append-only lists, but if your list can be reordered, filtered, sorted, or prepended to, index keys mean the DOM node at position i gets reused for whatever item now sits there — carrying its cached height with it.

Pass getItemKey to give items real identity:

<MasonrySnapGrid items={items} getItemKey={(item) => item.id} renderItem={...} />

What it changes per adapter:

  • React / Vue — becomes the key, so nodes move instead of being rebuilt.
  • Vanilla / Angular — enables keyed reconciliation, so updateItems() reuses existing elements instead of clearing the container. That preserves focus, text selection, scroll position inside items, and in-flight media playback.

Server-Side Rendering

Items are rendered into the initial HTML inside a responsive CSS grid, so they are in the page source for crawlers and painted before hydration.

  • The server renders every item inside a plain responsive CSS grid.
  • The browser paints that immediately — fast First Contentful Paint.
  • The client hydrates, measures item heights, and applies masonry transforms.
  • ResizeObserver keeps the layout correct from then on.

Because step 3 moves items from grid positions to masonry positions, expect one transition after hydration. Setting animate={false} makes it instant rather than animated.

Next.js

Add 'use client' in the App Router, since the component uses browser APIs after hydration:

'use client';
import MasonrySnapGrid from 'masonry-snap-grid-layout/react';
import 'masonry-snap-grid-layout/style.css';

No directive is needed in the Pages Router.

Nuxt

The Vue component works with SSR out of the box. Import the stylesheet in nuxt.config.ts:

export default defineNuxtConfig({
  css: ['masonry-snap-grid-layout/style.css'],
});

Recipes

Responsive image gallery
<MasonrySnapGrid
  items={photos}
  columns={{ 0: 2, 768: 3, 1280: 4 }}
  gutter={12}
  getItemKey={(photo) => photo.id}
  renderItem={(photo) => (
    <img
      src={photo.src}
      alt={photo.alt}
      width={photo.width}
      height={photo.height}
      loading="lazy"
      style={{ width: '100%', height: 'auto', display: 'block' }}
    />
  )}
/>

Passing width / height lets the browser reserve the correct box before decode, so there is nothing for self-healing to correct.

Infinite scroll
const [items, setItems] = useState(initial);

<MasonrySnapGrid
  items={items}
  getItemKey={(item) => item.id} // required: appended items must keep identity
  virtualize
  estimatedItemHeight={280}
  onLayout={({ containerHeight }) => {
    if (window.scrollY + window.innerHeight > containerHeight - 600) {
      loadMore().then((next) => setItems((prev) => [...prev, ...next]));
    }
  }}
  renderItem={(item) => <Card {...item} />}
/>;
Reading the resolved layout
<MasonrySnapGrid
  items={items}
  onLayout={(info) => {
    console.log(`${info.columnCount} columns of ${info.columnWidth}px`);
    console.log(`total height ${info.containerHeight}px via ${info.engine}`);
  }}
  renderItem={...}
/>

Engine Comparison

CSS MasonryJS Masonry
AvailabilityExperimental, behind flagsAll browsers
AnimationsLimitedSmooth transform transitions
SSRYesYes
PerformanceNative, GPUTransform-based, no DOM thrashing
VirtualizationNoYes — page or scroll container
Self-healingNativeYes — per-item observers
Column controlcolumns, or browser decidesExact columns / minColWidth

Browser Support

The JS engine works in every browser that can run the package's ES2020 output.

Two modern APIs are used, both optional:

APIUsed forWithout it
ResizeObserverResponsive columns and self-healing layoutLayout still runs; it just does not re-run on resize
CSS.supportsDetecting native CSS masonryFalls back to the JS engine

Both are feature-detected, so there is nothing to polyfill and no crash on older engines — you simply get a static layout. Server-side rendering touches neither.

Package Exports

EntryContentsmin+gzipmin+brotli
masonry-snap-grid-layoutVanilla JS class + TypeScript types2.8 kB2.5 kB
masonry-snap-grid-layout/reactReact component3.6 kB3.2 kB
masonry-snap-grid-layout/vueVue 3 component3.8 kB3.4 kB
masonry-snap-grid-layout/angularAngular standalone component (TS source)compiled by your build
masonry-snap-grid-layout/style.cssRequired stylesheet0.3 kB0.2 kB

Each figure includes every shared chunk that entry pulls in, and is enforced in CI by npm run size.

dist/ is published unminified — readable inside node_modules, and every bundler minifies it anyway — so the numbers above are measured after minification, matching what you actually ship and what bundlephobia reports. Loading straight from a CDN with no build step serves the unminified file instead: ~17 kB raw, ~5 kB gzipped over the wire for the React entry.

All exports are ESM and tree-shakeable. Importing /react includes no Vue or Angular code, and the Vanilla entry contains no virtualization or scroll-tracking code at all.

TypeScript

Every entry point is fully typed, and the item type flows through generically:

interface Photo {
  id: string;
  src: string;
  alt: string;
}

// `item` is inferred as Photo in renderItem and getItemKey
<MasonrySnapGrid<Photo>
  items={photos}
  getItemKey={(item) => item.id}
  renderItem={(item) => <img src={item.src} alt={item.alt} />}
/>;

The Vue component uses a generic <script setup> so the scoped slot is typed too, and the Angular component is generic over T.

Performance

  • No DOM thrashing. Widths are written in one pass, heights read in one pass, and transforms written in a final pass. Reads are never interleaved with writes.
  • Frame coalescing. Scroll, resize, item-resize, and image-load events all collapse into at most one layout per animation frame. A gallery of 200 images finishing simultaneously costs one relayout, not 200.
  • Width-only resize handling. Height changes are ignored, because layout sets the container height itself — reacting to it would feed back into a loop.
  • Stable ref callbacks. Items attach once instead of detaching and reattaching on every render.
  • GPU compositing via will-change: transform on layout items.
  • Bounded DOM through virtualization, with estimatedItemHeight avoiding the initial full mount.
  • Small. 3.6 kB min+gzip for the React entry including shared chunks, with a budget enforced in CI. See Package Exports for every entry point.

Running Examples Locally

Every framework has a full demo app in examples/, kept in step with this repo — they are typechecked against the local source in CI, so a renamed prop breaks the build rather than leaving a stale demo behind.

Build the library first so the examples can import from dist/:

npm install
npm run build
FrameworkCommandURL
Vanilla JScd examples/vanilla && npm install && npm run devhttp://localhost:5173
Reactcd examples/react && npm install && npm run devhttp://localhost:5173
Vue 3cd examples/vue && npm install && npm run devhttp://localhost:5173
Angularcd examples/angular && npm install && npm run devhttp://localhost:4200

What the demos show

Each app has live controls for every feature, plus a status bar reporting the engine in use and the resolved layout from onLayout:

ControlDemonstrates
Content: text / imagesSelf-healing. The images carry no width/height, so the grid is first measured against zero-height boxes and re-packs itself as each one decodes.
Columns: min width / fixed / breakpointsminColWidth versus a fixed columns count versus a mobile-first breakpoint map.
Scroll container: page / panelVirtualizing against the window versus an overflow: auto panel (React and Vue).
Estimated heightsestimatedItemHeight skipping the initial full mount on a large list (React and Vue).
Prepend / ShufflegetItemKey. Cards keep their own heights and content because identity travels with the data, not the index.
Layout mode: auto / jsNative CSS masonry detection versus forcing the JS engine.
Gutter, overscan, animateThe remaining layout and animation options.
FrameworkNotes
Vanilla JSDrives one instance through setOptions() — no destroy-and-rebuild on option changes.
ReactThe fullest demo: every feature above, including both virtualization modes.
Vue 3Feature parity with React, via the scoped slot and the @layout event.
AngularUses the standalone MasonrySnapGridComponent, so every control is a plain @Input. Virtualization is not available in Angular.

The hosted CodeSandbox links above are convenient but may lag behind this repo, since they pull the published package. The apps in examples/ are the version-matched reference.

Testing

251 tests across Vitest, Testing Library, Vue Test Utils, and direct Angular lifecycle tests — every adapter is covered.

AreaCovers
Layout corePlacement, shortest-column selection, tie-breaking, container height, fallback heights
ColumnsminColWidth derivation, fixed counts, breakpoint resolution, invalid-value fallbacks
Virtualization coreVisible-window maths, overscan, container offset, straddling items, estimate activation
Scroll coreWindow and element targets, frame coalescing, offset re-reads, cross-realm target detection
Measurement coreInitial-callback suppression, burst coalescing, image load / error, teardown, polyfills
Vanilla engineLifecycle, updateItems, setOptions, destroy, keyed reuse, observer teardown
ReactSSR output and warnings, layout modes, columns, onLayout, item identity, self-healing
React virtualizationViewport clipping, scrolling in and out of view, scroll containers, estimated heights
VueSlot rendering, SSR output, layout, columns, identity, self-healing, teardown
Vue virtualizationClipping, scroll tracking, scroll containers, estimated heights
AngularEngine construction, full input forwarding, layout output, keyed reuse, teardown
CSS fallbackEngine selection both ways, throwing/missing CSS, track lists, engine switching, teardown
Real SSR (Node)Import safety, markup, no clipping, no warnings, detection with no browser globals
npm test                  # run all tests
npm run typecheck         # core + React, Angular, and Vue SFC compilers
npm run lint              # ESLint, zero warnings tolerated
npm run format:check      # Prettier
npm run size              # gzipped bundle budget per entry point
npm run check:arch        # layer boundaries and import cycles
npm run check:package     # packs the tarball and verifies every export resolves
npm run build             # full production build
npm run verify            # everything above, in the order CI runs it

Each adapter is typechecked with the compiler that will actually compile it: tsc for the core and React, a separate Angular config (the Angular component ships as TypeScript source and compiles in your build), and vue-tsc for the SFC.

SSR is tested for real. tests/ssr.test.tsx runs in a pure Node environment with no window, document, CSS, ResizeObserver, or requestAnimationFrame — the same conditions as a Next.js or Nuxt server. Every other suite runs in jsdom, where those globals exist, so a renderToString test there cannot catch a module that touches the DOM at import time. The suite asserts the globals are absent before anything else, so it cannot pass vacuously.

Upgrading

1.2.x → 1.3.0

A drop-in upgrade — no breaking changes. Every new option is opt-in.

One behavioural change worth knowing: the layout is now self-healing by default, so grids containing images will relayout as those images decode. This corrects a real bug rather than changing a contract, but if you relied on the layout never re-running, set observeItemResize={false} and watchImages={false}.

If you use the Angular entry point, upgrading is requiredmasonry-snap-grid-layout/angular could not resolve in versions before 1.3.0. See the changelog for the full list.

FAQ

How do I create a masonry layout in React?

Install the package, import from masonry-snap-grid-layout/react, and pass items plus a renderItem function. There is no wrapper element to configure and no CSS to write beyond importing the stylesheet — see Quick Start.

Does it work with Next.js?

Yes. Items are server-rendered into the HTML, so they are crawlable and painted before hydration. In the App Router, add 'use client' to the file that imports the component, since it uses browser APIs after hydration. No directive is needed in the Pages Router. See Server-Side Rendering.

Does it work with Nuxt or Vue SSR?

Yes, out of the box. Register the stylesheet in nuxt.config.ts — see Nuxt.

Why are my items overlapping or leaving big gaps?

Almost always because item heights were measured before the content settled — usually unloaded images. This library relayouts automatically when images decode, fonts swap, or embeds resize, so it should self-correct within a frame.

If it does not, check that you have not set observeItemResize={false}, and that your items are not given a fixed height by CSS that hides the real content height. Adding width/height or aspect-ratio to images avoids the reflow entirely. See Images and Async Content.

How do I set a fixed number of columns?

Pass columns={3}. This overrides minColWidth. See Columns and Breakpoints.

How do I make the number of columns responsive?

Pass a breakpoint map keyed on minimum container width: columns={{ 0: 1, 640: 2, 1024: 3 }}. It reads like a min-width media query, and because it tracks the container rather than the viewport, a grid inside a sidebar responds to the sidebar.

Can I virtualize inside a scrollable div instead of the page?

Yes — pass scrollContainer an element or a React ref. See In a scroll container.

Does it support infinite scroll?

Yes. Use onLayout to watch containerHeight and append items, and pass getItemKey so appended items keep their identity. There is a worked example under Recipes.

How many items can it handle?

With virtualize and estimatedItemHeight, tens of thousands — only the visible window plus the overscan buffer is ever in the DOM, and the initial full mount is skipped entirely. See Very large lists.

Is virtualization available in Angular?

No. The Angular component wraps the Vanilla engine, which renders all items. Use React or Vue if you need virtualization.

Why do items shift slightly right after the page loads?

That is the SSR handoff. The server renders a plain responsive CSS grid; after hydration the client measures heights and applies masonry positions, which moves items once. Set animate={false} to make it instant instead of animated. See Server-Side Rendering.

How is this different from CSS columns or plain CSS Grid?

CSS columns fills each column top-to-bottom before starting the next, so reading order runs down each column — usually wrong for a feed. Plain CSS Grid aligns items to uniform rows, which leaves gaps under short items. Masonry fills across and packs each item into the shortest column, which is what produces the Pinterest look. Native CSS masonry solves this properly but is still experimental.

Do I need to install React, Vue, and Angular?

No. All three are optional peer dependencies — install only the one you use. Nothing from the others reaches your bundle, since each entry point is a separate ESM module.

How do I animate layout changes?

Animation is on by default in JS mode, using GPU-composited transform transitions. Tune it with transitionDuration, or disable it with animate={false}. Note that the native CSS masonry engine cannot animate — pin layoutMode="js" if animation matters.

Does it keep a sensible tab and screen-reader order?

Yes. Items are absolutely positioned, but the DOM order always matches your items array, so tab order and screen-reader order follow your data rather than the visual packing. As with any masonry layout, visual left-to-right order may differ from DOM order once columns pack unevenly.

Contributing

git clone https://github.com/khachatryan-dev/masonry-snap-grid-layout
cd masonry-snap-grid-layout
npm install
npm run verify      # lint, typecheck all adapters, test, build, size, package
  • Fork the repo
  • Create a feature branch
  • Keep npm run verify green
  • Open a pull request

Where to make a change. The layout algorithm, virtualization maths, scroll tracking, and measurement all live in src/core/ as framework-agnostic modules, split into model/ (pure logic), lib/ (browser primitives), and engine/ (DOM writers). The Vanilla, React, Vue, and Angular adapters are thin shells that consume src/core through its public API, so a fix in the core fixes every framework at once.

Layer boundaries and import cycles are enforced by npm run check:arch, so an adapter reaching into core/model — or the pure model reaching for a browser API — fails CI rather than passing review.

📐 ARCHITECTURE.md is the full map: what lives where, the dependency rules, and where a given kind of change belongs.

See CONTRIBUTING.md and the Code of Conduct.

Changelog

See CHANGELOG.md for release history.

Author

Built and maintained by Aram Khachatryan

GitHub Buy Me a Coffee

If this library saved you time, a ⭐ on GitHub helps others find it.

License

MIT © Aram Khachatryan

Keywords

masonry

FAQs

Package last updated on 27 Aug 2026

Related posts