i'm still a newbie in react js, i'm having a problem changing my react js code from class component to functional component. is there someone here can help me?
import React, { Component } from "react"; import { EditorState, Modifier, BlockMapBuilder, convertFromHTML, DefaultDraftBlockRenderMap, ContentBlock, } from "draft-js"; import { Map } from "immutable"; import { Editor } from "react-draft-wysiwyg"; import "react-draft-wysiwyg/dist/react-draft-wysiwyg.css";
const mapWithButton = Map({
button: {
element: "button",
},
}).merge(DefaultDraftBlockRenderMap);
function myBlockRenderer(contentBlock) {
const type = contentBlock.getType();
if (type === "button") {
return {
component: () => {
return (
<button
style={{ zIndex: 100 }}
onClick={() => console.log("doesn't seem to work :(")}
>
{contentBlock.getText()}
</button>
);
},
editable: false,
};
}
}
class CustomTextEditor extends Component {
editor;
constructor(props) {
super(props);
this.state = { editorState: EditorState.createEmpty() };
}
componentDidMount() {
this.focusEditor();
}
setEditor = (editor) => {
this.editor = editor;
};
focusEditor = () => {
if (this.editor) {
// this.editor.focusEditor();
console.log("1. Editor has the focus now");
}
};
onEditorStateChange = (editorState) => {
this.setState({
editorState,
});
};
sendTextToEditor = (text) => {
this.setState({
editorState: this.insertText(text, this.state.editorState),
});
this.focusEditor();
};
insertText = (text, editorState) => {
const htmlContent = convertFromHTML(text, undefined, mapWithButton);
console.log(htmlContent.contentBlocks.map((c) => c.toObject()));
const currentContent = editorState.getCurrentContent(),
currentSelection = editorState.getSelection();
const htmlContentMap = BlockMapBuilder.createFromArray(
htmlContent.contentBlocks
);
const newContent = Modifier.replaceWithFragment(
currentContent,
currentSelection,
htmlContentMap
);
const newEditorState = EditorState.push(
editorState,
newContent,
"insert-characters"
);
return EditorState.forceSelection(
newEditorState,
newContent.getSelectionAfter()
);
};
render() {
const { editorState } = this.state;
return (
<>
<Editor
ref={this.setEditor}
editorState={editorState}
wrapperClassName="demo-wrapper"
editorClassName="demo-editor"
onEditorStateChange={this.onEditorStateChange}
customBlockRenderFunc={myBlockRenderer}
/>
<button
type="button"
onClick={this.sendTextToEditor.bind(
this,
"<button>Button but click does not work</button><b>Bold text</b>, <i>Italic text</i><br/ ><br />" +
'<a href="http://www.facebook.com">Example link</a>'
)}
>
Copy sample text to editor
</button>
</>
);
}
}
export default CustomTextEditor;