Reputation: 39
I am working on a React component with an HTML editor.
Currently trying to use a WYSIWYG Editor from Draft.js (WYIWYG Draft.js)
The docs seem geared towards class-based components, but I am trying to use functional components.
I have HTML text coming from an API call & stored in a variable like so:
var values.overview = "<p>this is html text</p>"
I want this to be the initial value - visible and editable in the Editor component.
I've gotten as far as getting the text displayed, but I'm quite sure it's a very flawed approach:
const [editorState, setEditorState] = useState(EditorState.createWithContent(ContentState.createFromBlockArray(convertFromHTML(values.overview))));
and the component:
<Editor
editorState={editorState}
toolbarClassName="toolbarClassName"
wrapperClassName="wrapperClassName"
editorClassName="editorClassName"
/>
How can I update state based on user input?
Do I need to be using Content State for user input?
What is the best way to manage this state?
I've been stuck on this for a while now.
Upvotes: 2
Views: 2574
Reputation: 39
This seems to be working....
var overview = "<u>this is my text</u>";
const contentDataState = ContentState.createFromBlockArray(convertFromHTML(overview));
const editorDataState = EditorState.createWithContent(contentDataState);
const [editorState, setEditorState] = useState(editorDataState);
const onEditorStateChange = (editorStateData) => {
setEditorState(editorStateData);
};
const data = draftToHtml(convertToRaw(editorState.getCurrentContent()));
console.log(data);
return (
<>
<Editor
editorState={editorState}
onEditorStateChange={onEditorStateChange}
wrapperClassName="wrapperClassName"
editorClassName="editorClassName"
toolbarClassName="toolbar-class"
toolbar={{
options: ['inline', 'list', 'textAlign'],
inline: {
options: ['bold', 'italic', 'underline'],
},
list: {
options: ['unordered', 'ordered', 'indent', 'outdent'],
},
textAlign: {
options: ['left', 'center', 'right'],
},
}}
/>
</>
);
}
Upvotes: 1