useCanvasViewport
Overview
Editor hooks that tell a block which Method breakpoint tier the canvas is in — mobile, tablet, desktop or wide — by running media queries against the canvas iframe’s own window rather than the admin window.
- File: lib/blocks/hooks/useCanvasViewport.js
- Exports:
useCanvasViewport( view )(default),useCanvasWindow(),getMethodBreakpoints() - Breakpoints:
methodGlobalData.breakpoints, localised frommethod_get_block_breakpoints(); the lib/config.php defaults are the fallback
Block editor scripts run in the top admin window, so window.matchMedia there only ever describes the browser. The editor renders the post in an iframe whose width is the device preview or the resized canvas, and only that window’s media queries follow it. These hooks do what core’s block visibility does: useMediaQuery( query, view ) with the canvas window as view.
Signature
JavaScript
import useCanvasViewport, { useCanvasWindow, getMethodBreakpoints } from '../../hooks/useCanvasViewport';
const [ref, canvasWindow] = useCanvasWindow();
const blockProps = useBlockProps({ ref });
const tier = useCanvasViewport(canvasWindow); // 'mobile' | 'tablet' | 'desktop' | 'wide' | undefined
Parameters
useCanvasWindow()
- Returns:
[ref, canvasWindow]— a callback ref to attach to the block wrapper (throughuseBlockProps({ ref })) and theWindowthat element is rendered in,undefineduntil the ref is attached.
useCanvasViewport( view )
view: The window fromuseCanvasWindow().- Returns:
"wide"when the canvas is at leastwide_minwide, else"desktop"abovetablet_max, else"tablet"fromtablet_min, else"mobile";undefinedwhileviewis unknown. - Queries: Range syntax —
(width >= 768px),(width > 1199px),(width >= 1600px)— so the theme’s unit is used as is, with no +1 arithmetic.
getMethodBreakpoints()
- Returns:
{ mobile_max, tablet_min, tablet_max, wide_min }—methodGlobalData.breakpointsover the defaults (767px,768px,1199px,1600px).
Behavior
- The tier updates live: resizing the canvas or switching the device preview re-evaluates the queries, and the block re-renders.
- The tiers are the same four the frontend CSS uses, so a preview that reads the tier can show the value the page will use — the Swiper blocks initialise their preview with the tier’s per-view, spacing or width instead of Swiper’s own
breakpointsoption, which would evaluate against the admin window. - The Modal block compares the tier with its
fullscreenBelowsetting so the preview goes full screen at the same canvas widths as the page.
Usage by Blocks
| Block | Notes |
|---|---|
| Swiper | Resolves the tier for the live preview’s per-view / spacing / slide width. |
| Swiper Gallery | As above, since the beta23 rebuild. |
| Modal | Full-screen-below-a-tier preview. |
| Mapbox Map | useCanvasWindow() only — the preview needs the canvas window to load Mapbox GL JS into. |
Changelog
| Version | Description |
|---|---|
| 2.0.0-beta18 | Introduced, for the Swiper block’s canvas-aware preview (3064cd9). |