Access the editor instance with useEditor hooks
mainTo interact with the GrapesJS API from your custom React components, use the provided hooks. Because the editor is initialized asynchronously, you must handle the case where the editor might not be ready yet.
useEditor(): Returns the editor instance. Use this inside a component wrapped by<WithEditor />to ensure the editor is always defined when the component renders.useEditorMaybe(): Returns the editor instance if it exists, orundefinedif it hasn't been created yet. Use this for components that need to render immediately regardless of the editor's state.<WithEditor />: A wrapper component that prevents its children from rendering until the GrapesJS editor instance is fully created.
import GjsEditor, { WithEditor, useEditor, useEditorMaybe } from '@grapesjs/react';
function MyComponentWithUseEditor() {
// The `editor` is always defined.
const editor = useEditor();
return (...);
}
function MyComponentWithUseEditorMaybe() {
// The `editor` is not immediately available
const editor = useEditorMaybe();
return (
<div
<div>I will be rendered immediately</div
<div
Editor: { editor ? 'created' : 'not yet created' }.
</div
</div>
);
}
export default function CustomEditor() {
return (
<GjsEditor ...>
<WithEditor>
{/* This component won't be rendered until the editor is created */}
<MyComponentWithUseEditor/>
</WithEditor>
<MyComponentWithUseEditorMaybe/>
</GjsEditor>
);
}