Basic Plugin Structure
A Lexical plugin is a React component that:- Uses
useLexicalComposerContext()to access the editor - Registers listeners, commands, or transforms in
useEffect - Returns
null(or optional UI)
AutoFocus Plugin Example
A simple plugin that focuses the editor on mount:packages/lexical-react/src/LexicalAutoFocusPlugin.ts for the complete implementation.
Command Plugin Example
Register custom commands to handle user actions:Transform Plugin Example
Node transforms are called automatically when nodes of a specific type change:Update Listener Plugin
React to editor state changes:Mutation Listener Plugin
Listen to DOM mutations for specific nodes:Plugin with UI
Plugins can also render UI elements:Using Plugins
import { AutoFocusPlugin } from '@lexical/react/LexicalAutoFocusPlugin';
import { MyCustomPlugin } from './plugins/MyCustomPlugin';
import { LexicalComposer } from '@lexical/react/LexicalComposer';
import { RichTextPlugin } from '@lexical/react/LexicalRichTextPlugin';
import { ContentEditable } from '@lexical/react/LexicalContentEditable';
import { AutoFocusPlugin } from '@lexical/react/LexicalAutoFocusPlugin';
import { LexicalErrorBoundary } from '@lexical/react/LexicalErrorBoundary';
function Editor() {
return (
<LexicalComposer initialConfig={config}>
<RichTextPlugin
contentEditable={<ContentEditable />}
placeholder={<div>Enter text...</div>}
ErrorBoundary={LexicalErrorBoundary}
/>
<AutoFocusPlugin />
<MyCustomPlugin />
</LexicalComposer>
);
}
Plugin Cleanup
Always return cleanup functions fromuseEffect to avoid memory leaks:
mergeRegister from @lexical/utils:
Common Plugin Patterns
Toolbar Plugin
- Renders formatting buttons
- Dispatches
FORMAT_TEXT_COMMAND - Listens to selection changes to update button states
Autocomplete Plugin
- Listens to text input
- Shows suggestions based on context
- Inserts nodes when suggestion is selected
Validation Plugin
- Registers node transforms
- Enforces content rules
- Prevents invalid node structures
Analytics Plugin
- Registers update listeners
- Tracks user interactions
- Sends events to analytics service
Best Practices
- Return Cleanup: Always return cleanup functions from
useEffect - Use mergeRegister: Simplify cleanup with
mergeRegisterutility - Dependencies: Include
editorinuseEffectdependencies - Command Priority: Use appropriate priority levels for commands
- Performance: Debounce expensive operations in update listeners
- Error Handling: Wrap risky operations in try-catch blocks
See Also
- Guide: Working with Commands
- API Reference: LexicalComposer
- API Reference: React Plugins
- Examples:
packages/lexical-react/src/ - Playground:
packages/lexical-playground/src/plugins/