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.
JavaScript
x
55
55
1
import React from "react";
2
import { EditorState, ContentState } from "draft-js";
3
import { Editor } from "react-draft-wysiwyg";
4
import htmlToDraft from "html-to-draftjs";
5
import { stateFromHTML } from "draft-js-import-html";
6
import "react-draft-wysiwyg/dist/react-draft-wysiwyg.css";
7
8
export default class App extends React.Component {
9
constructor(props) {
10
super(props);
11
12
const contents = [
13
{
14
text: "Sample text",
15
HTML:
16
"<p style='text-align: center;'><span style='font-size:3em;'><strong>Sample text</strong></span></p>"
17
},
18
{
19
text: "Sample text2",
20
HTML:
21
"<p style='text-align: center;'><span style='font-size:3em;'><strong>Sample text2</strong></span></p>"
22
}
23
];
24
25
this.state = {
26
editorStates: contents.map((element) =>
27
EditorState.createWithContent(stateFromHTML(element.HTML))
28
)
29
};
30
}
31
32
render() {
33
return (
34
<>
35
{this.state.editorStates.map((element, index) => {
36
return (
37
<Editor
38
defaultEditorState={element}
39
onEditorStateChange={(editorState) => {
40
const newState = {
41
this.state
42
};
43
newState.editorStates[index] = editorState;
44
45
this.setState(newState);
46
}}
47
key={index}
48
/>
49
);
50
})}
51
</>
52
);
53
}
54
}
55
Can someone have enough experience to help me with this?
Advertisement
Answer
Try to change your code like this:
JavaScript
1
44
44
1
import React, { useState } from 'react';
2
import { EditorState, ContentState } from 'draft-js';
3
import { Editor } from 'react-draft-wysiwyg';
4
import htmlToDraft from 'html-to-draftjs';
5
import { stateFromHTML } from 'draft-js-import-html';
6
import 'react-draft-wysiwyg/dist/react-draft-wysiwyg.css';
7
8
const contents = [
9
{
10
text: 'Sample text',
11
HTML: "<p style='text-align: center;'><span style='font-size:3em;'><strong>Sample text</strong></span></p>",
12
},
13
{
14
text: 'Sample text2',
15
HTML: "<p style='text-align: center;'><span style='font-size:3em;'><strong>Sample text2</strong></span></p>",
16
},
17
];
18
19
export default App = () => {
20
const [editorStates, setEditorStates] = useState(
21
contents.map((element) =>
22
EditorState.createWithContent(stateFromHTML(element.HTML))
23
)
24
);
25
26
return (
27
<>
28
{editorStates.map((element, index) => {
29
return (
30
<Editor
31
defaultEditorState={element}
32
onEditorStateChange={(editorState) => {
33
const updatedState = [editorStates];
34
updatedState[index] = editorState;
35
setEditorStates(updatedState);
36
}}
37
key={index}
38
/>
39
);
40
})}
41
</>
42
);
43
};
44
You can store the editorStates
using the useState
hook, and update it using the provided function.