what I have tried , here i have added two button when user click value stores in state, than that state is passed to the editor , copy as a props . then I was trying to convert value to html code and then concat the copy prop then again convert to html to draft format, and then update the state, but i am not able to fix.
Codesandbox link : code
what i want when user click on button it should append with the text value in editor.
Able to add text based on clicked, but now problem is to append text based on cursor position , currently it adds to the end, i want to be added where the user points the cursor and then click the button it should be added there
Latest code : Updated code with add text functionality
Parent Component
import EditorWrapper from "./Editor";
export default function App() {
const [copy, setCopy] = useState("");
return (
<>
<div className="App">
<div className="d-flex">
<button
onClick={() => setCopy("Welcome")}
className="btn btn-primary me-2"
>
Welcome
</button>
<button
onClick={() => setCopy("Thank you")}
className="btn btn-primary"
>
Thank you
</button>
</div>
<EditorWrapper copy={copy} />
</div>
</>
Editor Component
import "./styles.css";
import React, { useState, useEffect } from "react";
import { Editor } from "react-draft-wysiwyg";
import { EditorState, ContentState, convertToRaw } from "draft-js";
import "react-draft-wysiwyg/dist/react-draft-wysiwyg.css";
import htmlToDraft from "html-to-draftjs";
import draftToHtml from "draftjs-to-html";
export default function EditorWrapper({ copy }) {
const initialState = () => EditorState.createEmpty();
const [editorState, setEditorState] = useState(initialState);
const onChange = async (value) => {
// const data = draftToHtml(convertToRaw(value.getCurrentContent()));
// console.log(data.concat(`<p>${copy}</p>`));
// const contentBlock = htmlToDraft(data);
// const contentState = ContentState.createFromBlockArray(
// contentBlock?.contentBlocks
// );
// const updateState = EditorState.createWithContent(contentState);
setEditorState(value);
};
return (
<Editor
editorState={editorState}
toolbarClassName="toolbarClassName"
wrapperClassName="wrapperClassName"
editorClassName="editorClassName"
onEditorStateChange={(value) => onChange(value)}
stripPastedStyles
ariaLabel="draftEditor"
/>
);
}
${copy}
`)` to the console and forgot actually adding it to `data` variable. – Moaaz Bhnas Oct 20 '21 at 14:23