Sometimes, we want to initiate a Draft.js editor with content within a React app.
In this article, we’ll look at how to initiate a Draft.js editor with content within a React app.
Initiate a Draft.js Editor with Content within a React App
To initiate a Draft.js editor with content within a React app, we can use the ContentState.createFromText
method to create the initial content for the text editor.
Then we can pass that into the EditorState.createWithContent
method to set the content state as the editor’s initial content.
For instance, we can write:
import { ContentState, Editor, EditorState } from "draft-js";
import { useRef, useState } from "react";
const content = ContentState.createFromText("<b>hello world</b>");
export default function App() {
const [editorState, setEditorState] = useState(() =>
EditorState.createWithContent(content)
);
const editor = useRef(null);
const focusEditor = () => {
editor.current.focus();
};
return (
<div
style={{ border: "1px solid black", minHeight: "6em", cursor: "text" }}
onClick={focusEditor}
>
<Editor
ref={editor}
editorState={editorState}
onChange={setEditorState}
placeholder="Write something!"
/>
</div>
);
}
We add:
const content = ContentState.createFromText("<b>hello world</b>");
to set “<b>hello world</b>”
to create the initial content of the editor,
Then we have:
const [editorState, setEditorState] = useState(() =>
EditorState.createWithContent(content)
);
to set the content
as the initial state of the editorState
, which has the initial value of the text editor which can be used by Draft.js’ Editor
component.
Then we set the editorState
prop to the editorState
state as its value.
The onChange
prop is set to the setEditorState
function that sets binds the editorState
to the input value of the editor.
Therefore, <b>hello world</b>
is the content of the editor when it’s loaded initially.
Conclusion
To initiate a Draft.js editor with content within a React app, we can use the ContentState.createFromText
method to create the initial content for the text editor.
Then we can pass that into the EditorState.createWithContent
method to set the content state as the editor’s initial content.