How To Build A Text Editor With Lexical and React
--
Lexical is a new framework for building rich text editors. Let’s build a simple WYSIWYG editor with it.
In April 2022, Meta open-sourced Lexical — “an extensible text editor framework”.
Given that it powers some of the most popular web apps in the world, it especially focuses on accessibility and performance. Among other things, by its native support for React 18.
This caught my eye since a lot of text editing experiences are inherently inaccessible and struggle performance-wise as things get more complicated. Furthermore, Lexical adopted a lot of paradigms of React which makes it fairly easy to pick it up as a React developer (although it is framework agnostic).
So, I decided to give it a try and build a simple WYSIWYG editor with it.
How To Setup Lexical with React
Lexical can be used with any framework of your choice — or without a framework at all. It even offers a @lexical/headless
package which lets you run the editor in a Node.js environment. This can come in handy sometimes (e.g. running Lexical on the server)!
In our example, however, we will use Lexical with React.
Setting up an editor with Lexical and React is fairly easy. First we need to install necessary packages:
npm i react react-dom lexical @lexical/react
Lexical ships with a React-specific package (@lexical/react
) that let you compose your first editor in just a breeze:
import { LexicalComposer } from '@lexical/react/LexicalComposer';
import { RichTextPlugin } from '@lexical/react/LexicalRichTextPlugin';
import { ContentEditable } from '@lexical/react/LexicalContentEditable';
import LexicalErrorBoundary from '@lexical/react/LexicalErrorBoundary';
type LexicalEditorProps = {
config: Parameters<typeof LexicalComposer>['0']['initialConfig'];
};
export function LexicalEditor(props: LexicalEditorProps) {
return (
<LexicalComposer initialConfig={props.config}>
<RichTextPlugin
contentEditable={<ContentEditable />}…