Knowledge Base/How to check if your code is rendered inside the Canvas editor or preview

How to check if your code is rendered inside the Canvas editor or preview

how-toDeveloperNextJS page routerNextJS app routerCanvasVue/Nuxt

The problem

To build experiences optimized for the editors and web producers, you often need to conditionally display components or adjust markup/style or even behavior depending on whether your components render in preview or editor. Uniform's SDK has special tools to inspect whether your application is rendered inside Canvas, the visual experience editor. On top of that, Canvas has two modes of operation - editor and preview .

edit-mode.gif

The solution

The solution is slightly different for different front-end frameworks.

Next.js App Router example

Each component has the context prop. You can access context.isContextualEditing to get a bool flag on whether the page is rendered inside Uniform Canvas. The context.previewMode will tell you the exact mode, preview, or edit

const YourComponent = ({ context }) => { const { previewMode, isContextualEditing } = context || {}; if(isContextualEditing) { console.log("If true, your app is running inside Uniform Canvas"); } if(previewMode === 'editor') { console.log("You are in Uniform Canvas editor mode"); } if(previewMode === 'preview') { console.log("You are in Uniform Canvas preview mode"); } return <div>hello</div>; }

Next.js Pages Router example

When checking in a component under the <UniformComposition> (technically any component registered to used with Uniform), you can access the previewMode value via useUniformContextualEditingState. You can find an usage example in the component starter kit text component. Here is a sample code:

import { useUniformContextualEditingState } from '@uniformdev/canvas-react'; ... const { previewMode, isContextualEditing } = useUniformContextualEditingState(); if(isContextualEditing) { console.log("If true, your app is running inside Uniform Canvas"); } if(previewMode === 'editor') { console.log("You are in Uniform Canvas editor mode"); } if(previewMode === 'preview') { console.log("You are in Uniform Canvas preview mode"); }

If you need to check outside of <UniformComposition> you can use this code:

// _context.previewData is the default Next.js Preview Data object, which can be accessed in getStaticProps or getServerProps const isUniformEditing = _context.previewData?.isUniformContextualEditing || false;

Vue/Nuxt examples

You can use an approach similar to the Pages Router example. Here is an example in a Uniform project. Sample code:

import { useUniformContextualEditingState } from "@uniformdev/canvas-vue"; ... const { previewMode, isContextualEditing } = useUniformContextualEditingState(); ... <pre>Is editing: {{ isContextualEditing }}</pre> <pre>Mode: {{ previewMode }}</pre>
Published: January 6, 2025