How to add Jodit Editor in a React App(Next.Js)

Soubhagyajit Borah • April 11, 2024


In this tutorial, we'll learn how to integrate the Jodit Rich Text Editor into a React application, specifically using Next.js. We also discuss discussed about the common problems and how to upload images, whether that is base64 or url. Jodit is a powerful WYSIWYG editor that provides a user-friendly interface for creating and editing rich text content.


Prerequisites:


  • Basic knowledge of React and Next.js.
  • Node.js installed on your machine.
  • Familiarity with npm or yarn for package management.


We are now good to go. Follow the steps shown below


Step1:You need to create a Next Js project(Or an existing project)

If you haven't already set up a Next.js project, you can create one using the following commands:


 npx create-next-app my-jodit-editor-app
#or
yarn create next-app


Now go to the folder using:

 cd my-jodit-editor-app


Step 2: Installing Jodit

Next, we need to install the Jodit package along with its React wrapper:

 npm install jodit-react
#or
yarn add jodit-react


Step 3: Creating the Editor Component

Create a new file named Editor.js inside the components directory of your Next.js project. This component will contain the Jodit editor.

Note: However, on the main code that is on the github, I implemented it directly on the index.js page, it is not recomend to implement it directly.

/* Imports */
import React, { useState, useRef, useMemo } from 'react';
import dynamic from 'next/dynamic';
import Head from 'next/head';

/* Using dynamic import of Jodit component as it can't render in server side*/
const JoditEditor = dynamic(() => import("jodit-react"), { ssr: false });

/*functions*/
export default function Home() {
  const editor = useRef(null); //declared a null value 
  const [content, setContent] = useState("Worlds best html page"); //declare using state

  /* The most important point*/
  const config = useMemo( //  Using of useMemo while make custom configuration is strictly recomended 
    () => ({              //  if you don't use it the editor will lose focus every time when you make any change to the editor, even an addition of one character
      /* Custom image uploader button configuretion to accept image and convert it to base64 format */
      uploader: {         
        insertImageAsBase64URI: true,
        imagesExtensions: ['jpg', 'png', 'jpeg', 'gif', 'svg', 'webp'] // this line is not much important , use if you only strictly want to allow some specific image format
      },
    }),
    []
  );
  /* function to handle the changes in the editor */
  const handleChange = (value) => {
    setContent(value);
  };

  return (
    <>
    {/* Below is a basic html page and we use Tailwind css to style*/}
    <Head>
      <title>Jodit Rich Text Editor on the Web | Soubhagyajit</title>
      <meta name='author' content='Soubhagyajit Borah'/>
    </Head>
    <main>
      <div className="h-screen w-screen flex items-center flex-col">
        <div className="m-10  flex flex-col items-center">
         <span className="text-2xl text-center">
          
        Jodit Rich Text Editor on the Web
        </span> 
        <div className='text-center'>Author : Soubhagyajit Borah</div>
        <div className='text-center'>visit <a href="https://www.soubhagyajit.com/blogs/adding-Jodit-js-:-rich-text-editor-to-a-react-(next.js)-application" target='_blank' className="text-blue-500">www.soubhagyajit.com</a> for more information</div>
        </div>
        <div className="h-full w-[90vw]">
        {/* This is the main initialization of the Jodit editor */}
          <JoditEditor 
            ref={editor}            //This is important
            value={content}         //This is important
            config={config}         //Only use when you declare some custom configs
            onChange={handleChange} //handle the changes
            className="w-full h-[70%] mt-10 bg-white"
            />
            <style>
              {`.jodit-wysiwyg{height:300px !important}`}
            </style>
        </div>

        <div 
        className="my-10 h-full w-[90vw]"
        >Preview:
        <div dangerouslySetInnerHTML={{ __html: content }}></div>

        </div>
      </div>
    </main>
    </>
  );
}


Lets breakdown the code:

1. Imports


 import React, { useState, useRef, useMemo } from 'react';
 import dynamic from 'next/dynamic';
 import Head from 'next/head';


  • This section imports necessary modules and components for the React application.
  • useState: Hook for managing state within functional components.
  • useRef: Hook for creating a mutable reference.
  • useMemo: Hook for memoizing values to optimize performance.
  • dynamic: Function provided by Next.js for dynamic importing of components.
  • Head: Component provided by Next.js for managing the head of the document (e.g., setting title, meta tags).


2. JoditEditor Component


 const JoditEditor = dynamic(() => import("jodit-react"), { ssr: false });


This line imports the JoditEditor component dynamically, ensuring it's not rendered on the server side ({ ssr: false }) which is necessary for components that rely on the browser environment.


3. Home Component


 export default function Home() {


This defines a functional component named Home which serves as the main component of the application.


4. State and Refs


 const editor = useRef(null);
 const [content, setContent] = useState("Worlds best html page");


  • 'editor' is a mutable reference used to access the JoditEditor component.
  • 'content' is a state variable that holds the HTML content of the editor.
  • 'setContent' is a function used to update the content state.


5. Configuration


 const config = useMemo(() => ({
   uploader: {
     insertImageAsBase64URI: true,
     imagesExtensions: ['jpg', 'png', 'jpeg', 'gif', 'svg', 'webp']
   },
 }), []);


  • This config object is memoized using useMemo and contains custom configuration options for the JoditEditor.
  • In this case, it configures the image uploader to accept images and convert them to base64 format, and specifies allowed image extensions.


6. handleChange Function

 const handleChange = (value) => {
   setContent(value);
 };

  • This function updates the content state with the new HTML content whenever there is a change in the editor.


7. JSX Markup

  • The JSX markup within the return statement defines the layout and structure of the page.
  • It includes a Head component for managing document metadata, a heading, author information, the JoditEditor component, and a preview section.


8. Styling


  {`.jodit-wysiwyg{height:300px !important}`}


  • This inline style adjusts the height of the JoditEditor component.

9. Preview Section

 <div dangerouslySetInnerHTML={{ __html: content }}></div>


  • This div renders the HTML content stored in the content state variable.
  • It uses the dangerouslySetInnerHTML prop to render HTML content as React elements, which is necessary for displaying rich text content.


These are the breakdowns. Hope it will help you.


Final Step : Running Your Next.js Application


Finally, you can run your Next.js application using the following command:

 npm run dev
#or
yarn dev


Navigate to http://localhost:3000 in your web browser to see the Jodit Rich Text Editor integrated into your Next.js application. That's it! You've successfully integrated the Jodit Rich Text Editor into your React (Next.js) application. Feel free to customize the editor's configuration and styling according to your requirements.


Happy coding!


Downloadable files:


Github : https://github.com/soubhagyajit/jodit

Try on the web : https://jodit-editor-on-the-web.soubhagyajit.com/

I am currently updating the UI. If you notice any bug please Report me.

Close
Soubhagyajit Borah
Developed by Soubhagyajit Borah ㅤ
© Copyright . All right reserved.