I need to convert the given class component into a functional one.
I'm working with outputting an array of multiple Editors draft-js and I'm having some trouble outputting them. On the internet, I found a working class component with an array of them, but I can't convert it into a functional component for TS or JS.
import React from "react";
import { EditorState, ContentState } from "draft-js";
import { Editor } from "react-draft-wysiwyg";
import htmlToDraft from "html-to-draftjs";
import { stateFromHTML } from "draft-js-import-html";
import "react-draft-wysiwyg/dist/react-draft-wysiwyg.css";
export default class App extends React.Component {
constructor(props) {
super(props);
const contents = [
{
text: "Sample text",
HTML:
"<p style='text-align: center;'><span style='font-size:3em;'><strong>Sample text</strong></span></p>"
},
{
text: "Sample text2",
HTML:
"<p style='text-align: center;'><span style='font-size:3em;'><strong>Sample text2</strong></span></p>"
}
];
this.state = {
editorStates: contents.map((element) =>
EditorState.createWithContent(stateFromHTML(element.HTML))
)
};
}
render() {
return (
<>
{this.state.editorStates.map((element, index) => {
return (
<Editor
defaultEditorState={element}
onEditorStateChange={(editorState) => {
const newState = {
...this.state
};
newState.editorStates[index] = editorState;
this.setState(newState);
}}
key={index}
/>
);
})}
</>
);
}
}
Can someone have enough experience to help me with this?
Try to change your code like this:
import React, { useState } from 'react';
import { EditorState, ContentState } from 'draft-js';
import { Editor } from 'react-draft-wysiwyg';
import htmlToDraft from 'html-to-draftjs';
import { stateFromHTML } from 'draft-js-import-html';
import 'react-draft-wysiwyg/dist/react-draft-wysiwyg.css';
const contents = [
{
text: 'Sample text',
HTML: "<p style='text-align: center;'><span style='font-size:3em;'><strong>Sample text</strong></span></p>",
},
{
text: 'Sample text2',
HTML: "<p style='text-align: center;'><span style='font-size:3em;'><strong>Sample text2</strong></span></p>",
},
];
export default App = () => {
const [editorStates, setEditorStates] = useState(
contents.map((element) =>
EditorState.createWithContent(stateFromHTML(element.HTML))
)
);
return (
<>
{editorStates.map((element, index) => {
return (
<Editor
defaultEditorState={element}
onEditorStateChange={(editorState) => {
const updatedState = [...editorStates];
updatedState[index] = editorState;
setEditorStates(updatedState);
}}
key={index}
/>
);
})}
</>
);
};
You can store the editorStates
using the useState
hook, and update it using the provided function.