Repository navigation
Replies: 2 comments
|
I get it work! But not sure if this is the best way to do it. import { $generateHtmlFromNodes, $generateNodesFromDOM } from '@lexical/html';
import { AutoFocusPlugin } from '@lexical/react/LexicalAutoFocusPlugin';
import { LexicalComposer } from '@lexical/react/LexicalComposer';
import { ContentEditable } from '@lexical/react/LexicalContentEditable';
import { EditorRefPlugin } from '@lexical/react/LexicalEditorRefPlugin';
import { LexicalErrorBoundary } from '@lexical/react/LexicalErrorBoundary';
import { HistoryPlugin } from '@lexical/react/LexicalHistoryPlugin';
import { OnChangePlugin } from '@lexical/react/LexicalOnChangePlugin';
import { RichTextPlugin } from '@lexical/react/LexicalRichTextPlugin';
import { $getRoot, $insertNodes, LexicalEditor } from 'lexical';
import React, { useEffect, useRef } from 'react';
import styles from './RichEditor.module.css';
export interface RichEditorProps {
value?: string;
onChange?: (value: string) => void;
placeholder?: string;
}
export default function RichEditor({ value = '', onChange, placeholder }: RichEditorProps) {
const valueRef = useRef('');
const editorRef = useRef<LexicalEditor>(null);
useEffect(() => {
if (value !== valueRef.current) {
const parser = new DOMParser();
const dom = parser.parseFromString(value, 'text/html');
editorRef.current.update(() => {
const nodes = $generateNodesFromDOM(editorRef.current, dom);
const root = $getRoot();
root.clear();
$insertNodes(nodes);
valueRef.current = value;
});
}
}, [value]);
return (
<div className={styles.root}>
<LexicalComposer
initialConfig={{
namespace: 'comment-editor',
onError: console.error,
}}
>
<RichTextPlugin
contentEditable={
<ContentEditable
className={styles.content}
aria-placeholder={placeholder}
placeholder={<div className={styles.placeholder}>{placeholder}</div>}
/>
}
ErrorBoundary={LexicalErrorBoundary}
/>
<OnChangePlugin
onChange={() => {
editorRef.current.read(() => {
const html = $generateHtmlFromNodes(editorRef.current);
valueRef.current = html;
onChange?.(html);
});
}}
/>
<EditorRefPlugin editorRef={editorRef} />
<HistoryPlugin />
<AutoFocusPlugin />
</LexicalComposer>
</div>
);
} |
0 replies
|
its better if we dont make it controlled imo, messes up with the undo and redo functionalities of the lexical editor |
0 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Uh oh!
There was an error while loading. Please reload this page.
Uh oh!
There was an error while loading. Please reload this page.
In my React project, a rich text field is part of a Form (powered by antd). The Form require each input component has value & onChange prop. So I want to wrap Lexical into something like this:
But I cannot find a way to replace entire editor content with html. Any ideas?
All reactions