react-md-editor
react-md-editor copied to clipboard
How to send command from external component to MDEditor
I'm trying to send bold command from different component (like from a button on my app navigation bar ) to MDEditor. Is there a way for me to achieve this behavior?
@jamesnguyen30 example: https://codesandbox.io/embed/markdown-editor-for-react-forked-x0n0z7?fontsize=14&hidenavigation=1&theme=dark
import React from "react";
import ReactDOM from "react-dom";
import MDEditor, {
selectWord,
getStateFromTextArea
} from "@uiw/react-md-editor";
// No import is required in the WebPack.
// import "@uiw/react-md-editor/dist/markdown-editor.css";
const mkdStr = `
# Markdown Editor
`;
function App() {
const [value, setValue] = React.useState(mkdStr);
const editorRef = React.useRef();
function handleBold() {
if (editorRef.current) {
const { textApi, textArea } = editorRef.current.commandOrchestrator;
const state = getStateFromTextArea(textArea);
console.log("REF:", editorRef.current);
// Adjust the selection to encompass the whole word if the caret is inside one
const newSelectionRange = selectWord({
text: state.text,
selection: state.selection
});
const state1 = textApi.setSelectionRange(newSelectionRange);
// Replaces the current selection with the bold mark up
const state2 = textApi.replaceSelection(`**${state1.selectedText}**`);
// Adjust the selection to not contain the **
textApi.setSelectionRange({
start: state2.selection.end - 2 - state1.selectedText?.length,
end: state2.selection.end - 2
});
}
}
return (
<div className="container">
<h3>Auto</h3>
<button onClick={handleBold}>Button</button>
<MDEditor
ref={editorRef}
height={200}
value={value}
onChange={setValue}
/>
</div>
);
}
ReactDOM.render(<App />, document.getElementById("container"));