Search code examples
javascriptreactjstinymce

TinyMce not getting updated state value in the custom toolbar Action


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

  1. Click the 'My Custom Button' button and check the console output.
  2. Update the state by clicking the add button which updates the state value.
  3. Now again click 'My Custom Button' and observe we are still getting the initial state which is initially set while component creation.

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?


Solution

  • 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);