DEV Community

loading...
Cover image for How to add Ckeditor5 in your Next JS, react App

How to add Ckeditor5 in your Next JS, react App

devzversity profile image Apu Chakraborty ・1 min read

I am creating a fresh CRA & here is my project directory

Alt Text

Before we going started, you need to add this npm package first, to install please paste the below code into your terminal.

npm i @ckeditor/ckeditor5-react
npm i @ckeditor/ckeditor5-build-classic
Enter fullscreen mode Exit fullscreen mode

create a components folder under src folder and create a Editor component under components/Editor.js & use this code

import React, { useEffect, useRef } from "react";

function Editor({ onChange, editorLoaded, name, value }) {
  const editorRef = useRef();
  const { CKEditor, ClassicEditor } = editorRef.current || {};

  useEffect(() => {
    editorRef.current = {
      CKEditor: require("@ckeditor/ckeditor5-react").CKEditor, // v3+
      ClassicEditor: require("@ckeditor/ckeditor5-build-classic")
    };
  }, []);

  return (
    <div>
      {editorLoaded ? (
        <CKEditor
          type=""
          name={name}
          editor={ClassicEditor}
          data={value}
          onChange={(event, editor) => {
            const data = editor.getData();
            // console.log({ event, editor, data })
            onChange(data);
          }}
        />
      ) : (
        <div>Editor loading</div>
      )}
    </div>
  );
}

export default Editor;

Enter fullscreen mode Exit fullscreen mode

Now go to your app.js or wherever you want to use this editor just import Editor Component and use this

import React, { useState, useEffect } from "react";
import "./styles.css";
import Editor from "./Editor";

export default function App() {
  const [editorLoaded, setEditorLoaded] = useState(false);
  const [data, setData] = useState("");

  useEffect(() => {
    setEditorLoaded(true);
  }, []);

  return (
    <div className="App">
      <h1>ckEditor 5</h1>

      <Editor
        name="description"
        onChange={(data) => {
          setData(data);
        }}
        editorLoaded={editorLoaded}
      />

      {JSON.stringify(data)}
    </div>
  );
}

Enter fullscreen mode Exit fullscreen mode

visit ckEditor5 documentation to add more features - https://ckeditor.com/docs/ckeditor5/latest/examples/builds/classic-editor.html

you can clone repo

GitHub logo apuchakraborty / ckEditor5-implement

Created with CodeSandbox

ckEditor5-implement

Created with CodeSandbox

go to - cd /projectdir

npm install & npm start to run

You can use this code in codesSandbox
Here is your editor -

Discussion (0)

Forem Open with the Forem app