How to use WYSIWYG CK Editor 5 in React

A WYSIWYG editor is a program that allows users to create and edit documents in a graphical interface, without having to type code. This type of editors is often used for creating web pages, blog posts, etc. These editors make it very easy for the user to customize their text/page.

There are many WYSIWYG web-based editors available to users. CKEditor is one of the most common editors among them. In this article, we will see how we can use CK Editor 5 in our React app.

There is a react-draft-wysiwyg editor available for React, but using it in React app is very difficult and it has very less features as compared to CKEditor 5.

STEP 1 :

Let’s start by creating a new React app, if you want to use it in your existing app then skip this step :

npx create-react-app my-app
cd my-app

STEP 2 :

Now install CKEditor 5 Component for React and start the development server.

npm install --save @ckeditor/ckeditor5-react @ckeditor/ckeditor5-build-classic
npm start

STEP 3 :

Import required packages and create CKEditor component.

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

const App = () => {

     //On CKEditor text change !
     const onWriterChange = (event, editor) => {
           console.log("Some changes !");
      }

     //instance for CKEditor
     const [editor, setEditor] = useState(null);


    return (

        <CKEditor
          editor={ClassicEditor}      
          onReady={(e) => setEditor(e)}
          onChange={onWriterChange}
          config={{
                   toolbar: [['Bold'], ['Italic'], ['Underline'], ['Heading'], 
                            ['BulletedList'],   ['NumberedList'], ['Link']]
          }}
         />
    
    );

}

Great! We have successfully set up CKEditor in our React App.

You can set the minimum and maximum height of your CKEditor by using ‘ck-editor__editable_inline‘ class.

Setting Height :

.ck-editor__editable_inline{
  min-height: 80vh !important;
  max-height: 80vh !important;
}

Getting Data Programmatically :

To get CKEditor data :

editor.data.get();

Setting Data Programmatically :

To set CKEditor data :

editor.data.set("New Data !");

Appending Data Programmatically :

To append data in CKEditor :

//Append text to the cursor position
editor.model.change(writer => {
                    writer.insert("New Appended Data !", editor.model.document.selection.getFirstPosition());
                });

//Appending text to end of the editor 
editor.model.change(writer => {
                    writer.insert("New Appended Data !","end");
                });

Related Posts