2

I want to create a custom plugin for CKEditor 5 in react.js like what is done in:

StackOverFlow question: CKEditor 5 insert image by external url

CKEditor documentation: Creating a simple plugin

In the above examples when the plugin is clicked the code below executes and user enters the image URL:

const imageUrl = prompt( 'Image URL' );

which is in init() method of the plugin class. But what I'm intending to do is:

When the custom plugin is clicked I want a react component to open, then user selects an image and the URL of the selected image gets passed to CKEditor to be inserted. I've read lots of articles and Stackoverflow Q&As but still I don't know how to manage the click event of the plugin in React to open the component and pass the URL to CKEditor.

P.S: I'm using a build of CKEditor which I'm customizing and building it myself (like this article). So I'm NOT integrating CKEditor into my project which is another option of using it in React.

Moj.H
  • 75
  • 12

1 Answers1

0

I could not find the exact solution. Instead, I ended up using a button next to CKEditor in order to insert images in a way that the whole process of inserting is under control of React.

import React from "react";
import { useState } from "react";
import { CKEditor } from "@ckeditor/ckeditor5-react";
import ClassicEditor from "@ckeditor/ckeditor5-build-classic";

const MyEditor = () => {
  const [editorInstance, setEditorInstance] = useState("");
  const insertImage = () => {
    const imageUrl = prompt("Image URL"); //the process of getting the image's url in React
                                          //here, it is only a prompt but it could be any function that is managed in React
    editorInstance.model.change((writer) => {
      const imageElement = writer.createElement("image", {
        src: imageUrl,
      });
      // Inserting the image in the current selection location.
      editorInstance.model.insertContent(
        imageElement,
        editorInstance.model.document.selection
      );
    });
  };
  return (
    <div className="container">
      <button onClick={insertImage}> Insert Image from Media Library </button>
      <CKEditor
        editor={ClassicEditor}
        onReady={(editor) => {
          setEditorInstance(editor);
        }}
      />
    </div>
  );
};

export default MyEditor;

This is what I did in the above code:

  • I saved the instant of the CKEditor in onReady event.
  • I used the instance (editorInstance) in inserImage method.
  • In insertImage method I got the image URL from a function.
  • Then I inserted my desired content (here, an image) in the editor by using editorInstance.model.change and editorInstance.model.insertContent.
Moj.H
  • 75
  • 12