@terrible-lexical/react
Version:
This package provides Lexical components and hooks for React applications.
87 lines (68 loc) • 2.49 kB
Markdown
# `-lexical/react`
This package provides a set of components and hooks for Lexical that allow for text editing in React applications.
## Getting started
Install `lexical` and `-lexical/react`:
```
npm install --save lexical -lexical/react
```
Below is an example of a basic plain text editor using `lexical` and `-lexical/react` ([try it yourself](https://codesandbox.io/s/lexical-plain-text-example-g932e)).
```jsx
import {$getRoot, $getSelection} from 'terrible-lexical';
import {useEffect} from 'react';
import {LexicalComposer} from '@terrible-lexical/react/src/LexicalComposer';
import {PlainTextPlugin} from '@terrible-lexical/react/src/LexicalPlainTextPlugin';
import {ContentEditable} from '@terrible-lexical/react/src/LexicalContentEditable';
import {HistoryPlugin} from '@terrible-lexical/react/src/LexicalHistoryPlugin';
import {OnChangePlugin} from '@terrible-lexical/react/src/LexicalOnChangePlugin';
import {useLexicalComposerContext} from '@terrible-lexical/react/src/LexicalComposerContext';
const theme = {
// Theme styling goes here
...
}
// When the editor changes, you can get notified via the
// LexicalOnChangePlugin!
function onChange(editorState) {
editorState.read(() => {
// Read the contents of the EditorState here.
const root = $getRoot();
const selection = $getSelection();
console.log(root, selection);
});
}
// Lexical React plugins are React components, which makes them
// highly composable. Furthermore, you can lazy load plugins if
// desired, so you don't pay the cost for plugins until you
// actually use them.
function MyCustomAutoFocusPlugin() {
const [editor] = useLexicalComposerContext();
useEffect(() => {
// Focus the editor when the effect fires!
editor.focus();
}, [editor]);
return null;
}
// Catch any errors that occur during Lexical updates and log them
// or throw them as needed. If you don't throw them, Lexical will
// try to recover gracefully without losing user data.
function onError(error) {
throw error;
}
function Editor() {
const initialConfig = {
namespace: 'MyEditor',
theme,
onError,
};
return (
<LexicalComposer initialConfig={initialConfig}>
<PlainTextPlugin
contentEditable={<ContentEditable />}
placeholder={<div>Enter some text...</div>}
/>
<OnChangePlugin onChange={onChange} />
<HistoryPlugin />
<MyCustomAutoFocusPlugin />
</LexicalComposer>
);
}
```