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 .
The solution
The solution is slightly different for different front-end frameworks.
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>;
}
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;