What are Commands?
Commands in Lexical are:- Type-safe event dispatchers
- Priority-based with propagation control
- Decoupled from implementation
- Used for keyboard events, formatting, custom actions, and more
Creating Commands
Create a command usingcreateCommand():
Dispatching Commands
Dispatch commands usingeditor.dispatchCommand():
Registering Command Handlers
Register handlers witheditor.registerCommand():
Command Priority
Lexical supports 5 priority levels (highest to lowest):Command Propagation
Handlers can control propagation by their return value:true- Stop propagation (command handled)false- Continue to next handler
Built-in Commands
Lexical provides many built-in commands:Text Formatting
Text Insertion
Deletion
Keyboard Events
Clipboard
History
Selection
packages/lexical/src/LexicalCommands.ts for all built-in commands.
Custom Command Examples
Simple Command
Command with Payload
Conditional Handler
Best Practices
- Type Safety: Always define payload types for commands
- Return Values: Return
trueto stop propagation,falseto continue - Priority: Use appropriate priority levels for your use case
- Cleanup: Always clean up command listeners
- Updates: Wrap mutations in
editor.update()when handling commands - Naming: Use descriptive, ACTION_NOUN format (e.g.,
INSERT_IMAGE_COMMAND) - Export: Export commands from a central location for reusability
See Also
- Guide: Creating Plugins
- API Reference: Commands
- API Reference: LexicalEditor
- Source:
packages/lexical/src/LexicalCommands.ts