I want to access the update state value in the custom toolbar action of the TinyMCE but get the initial value every time.
Sample Code:
function App() {
const [state, setState] = React.useState(0);
const handleAction = (editor) => {
console.log("State", state); // getting initial state always
};
return (
<>
<button onClick={() => setState(state + 1)}>Add me</button>
<p>State: {state}</p>
<Editor
apiKey="XXX"
init={{
toolbar: "myCustomToolbarButton",
setup: (editor) => {
editor.ui.registry.addButton("myCustomToolbarButton", {
text: "My Custom Button",
onAction: (editor) => {
// alert("Button clicked!" + state)
handleAction(editor);
}
});
}
}}
/>
</>
);
}
I have created reproducible code here.
Step to reproduce
I want to access the update state in the custom toolbar action is there any way to do that or any workaround is going to be very helpful?
You can pass the state down to the component and then read the current value from props using a ref:
import React from "react";
import ReactDOM from "react-dom";
import { Editor } from "@tinymce/tinymce-react";
function App() {
const [state, setState] = React.useState(0);
const editor = React.useRef(null);
const handleAction = () => {
console.log(editor.current.props.state);
};
return (
<>
<button onClick={() => setState(state + 1)}>Add me</button>
<p>State: {state}</p>
<Editor
ref={editor}
state={state}
apiKey="XXX"
init={{
toolbar: "myCustomToolbarButton",
setup: (editor) => {
editor.ui.registry.addButton("myCustomToolbarButton", {
text: "My Custom Button",
onAction: handleAction
});
}
}}
/>
</>
);
}
const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);