There is a React project and CKEditor 5 custom classic build.
Let's say we have a React component App which renders <CKEditor5 /> as a part of JSX. As for CKEditor itself, its toolbar has a custom button.
export const App = () => {
// It should be executed on click
const callbackToRun = useCallback(() => {
// any logic to execute on toolbar's button click
}, []);
return (
// CKE has a custom button in a toolbar. We'd like to run a callback when it is pressed.
<CKEditor5 />
);
}
What is an optimal approach to run a React logic (aka function/callback) that resides in the parent React component 'App' when we click on a button on CKE5 toolbar?
From what I think, there are such options as:
- Pass a callback as a part of config, extract it from a config when we click on a toolbar button inside a custom command.
export const App = () => {
const callbackToRun = useCallback(() => {}, []);
return (
<CKEditor5 config={callbackToRun} />
);
}
Next, we implement a basic command that extracts callback from a config and run it. The command is bound to a button click as a part of UI CKEditor5 logic (skipping this part of code, it is pretty common).
import { Command } from '@ckeditor/ckeditor5-core';
export class HandleToolbarButtonClickCommand extends Command {
execute() {
this.editor.config.get('callbackToRun')();
}
}
- Second possible approach is to get an instance of editor to React parent component. Then listen to execute event or similar event.
export const App = () => {
const editorInstance = useRef(null);
const handleReady = (editor) => editorInstance.current = editor;
const callbackToRun = useCallback(() => {}, []);
// ??? Should we listen to execute command somehow or toolbar button click somehow?
useEffect(() => {
// Pseudo code below
// editorInstance.listenTo(..., callbackToRun);
}, []);
return (
<CKEditor5 onReady={handleReady} />
);
}
What is the best way to handle a such situation when the part of react logic must be executed on a CKEditor5 toolbar button click?