editor.js: [Bug] Double codex editor in Reactjs

I’am trying to setup editor.js in my React app. But there is a weird situation in my project. Let me demonstrate: image image

There is second codex-editor which is I don’t need it. Also the second codex-editor is also main(?) editor. When I console output, it shows the second editor’s values: image My React app code:

import EditorJS from "@editorjs/editorjs";
import Header from "@editorjs/header";
import List from "@editorjs/list";
import "./App.scss";

function App() {
  const editor = new EditorJS({
    /**
     * Id of Element that should contain the Editor
     */
    holder: "editorjs",

    /**
     * Available Tools list.
     * Pass Tool's class or Settings object for each Tool you want to use
     */
    tools: {
      header: {
        class: Header,
        inlineToolbar: ["link"],
      },
      list: {
        class: List,
        inlineToolbar: true,
      },
    },
  });
  const onClickHandler = () => {
    editor
      .save()
      .then((outputData) => {
        console.log("Article data: ", outputData.blocks);
      })
      .catch((error) => {
        console.log("Saving failed: ", error);
      });
  };

  return (
    <div className="App">
      <div id="editorjs"></div>
      <button onClick={onClickHandler}>Add</button>
    </div>
  );
}

export default App;

About this issue

  • Original URL
  • State: open
  • Created 4 years ago
  • Comments: 16 (3 by maintainers)

Most upvoted comments

Only using useEffect doesn’t prevent from rendering twice. Using state to check editorjs instance exist was working for me though I’m not sure this is correct way. d

  const id = useId();
  const [editor, setEditor] = useState<EditorJS | null>(null);
  useEffect(() => {
    setEditor((prevEditor) => {
      if (!prevEditor) {
        return new EditorJS({
          holder: id,
        });
      }
      return null;
    });
    return () => {
      if (editor) {
        editor.destroy();
      }
    };
  }, []);
  return <div id={id} />;

This prevents initializing 2 instances of EditorJS object. This approach works for me 😃

import React, { useEffect, useState } from "react";
import EditorJS from "@editorjs/editorjs";

export default function Editor() {
  const [isMounted, setIsMounted] = useState(false);

  useEffect(() => {
    if (!isMounted) return;
    const editor = new EditorJS({...});
  }, [isMounted]);

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

  return (
    <>
      <div
        id="editorjs"
        className="editor-js-formats border border-zinc-300 rounded-xl p-6"
      />
    </>
  );
}

I successfully avoided rendering twice with the following code:

// Editor.tsx
import { useEffect, useRef, useState } from 'react';

import EditorJS, { type LogLevels, type OutputData } from '@editorjs/editorjs';
import Header from '@editorjs/header';
import _ from 'lodash';

const DEFAULT_INITIAL_DATA: OutputData = {
	time: new Date().getTime(),
	blocks: [
		{
			type: 'header',
			data: {
				text: 'This is my awesome editor!',
				level: 1,
			},
		},
	],
};

const EDITOR_HOLDER_ID = 'editorjs';

const Editor = (/* _props: any */) => {
	const ejInstance = useRef<EditorJS | null>();
	const [editorData, setEditorData] = useState(() => {
		return DEFAULT_INITIAL_DATA;
	});

	const initEditor = () => {
		const editor = new EditorJS({
			holder: EDITOR_HOLDER_ID,
			logLevel: 'ERROR' as LogLevels,
			data: editorData,
			// onReady: () => {
			// 	ejInstance.current = editor;
			// },
			onChange: async (api, _event) => {
				const content = await api.saver.save();
				setEditorData(content);
			},
			autofocus: true,
			tools: {
				header: Header,
			},
		});

		return editor;
	};

	// This will run only once
	useEffect(() => {
		if (_.isNil(ejInstance.current)) {
			const editor = initEditor();

			ejInstance.current = editor;
		}

		return () => {
			if (ejInstance.current?.destroy) {
				ejInstance.current?.destroy();
				ejInstance.current = null;
			}
		};
		// eslint-disable-next-line react-hooks/exhaustive-deps
	}, []);

	return <div id={EDITOR_HOLDER_ID} />;
};

export default Editor;

Hi, I face the same issue. But I have found this answer from stackoverflow here.

I tried to build my app and there is no issue.

For development, I comment ReactStrictMode like this :

ReactDOM.createRoot(document.getElementById("root") as HTMLElement).render(
  // <React.StrictMode>
  <QueryClientProvider client={queryClient}>
    <ConfigProvider theme={CustomTheme}>
      <RecoilRoot>
        <RouterProvider router={routes} />
      </RecoilRoot>
    </ConfigProvider>
  </QueryClientProvider>
  // </React.StrictMode>
);

Also find the reason why it’s rendered twice on Strict Mode from geeksforgeeks.org : image

Hope it helps!

Hi, It is because of rendering component twice, to solve this problem, when you initilize the editor in useEffect, use empty braces [] as useEffect’s dependency, so anything in useEffect will render once per each component call. And in the useEffect, return a cleanup function which destroy the editor when component detaches from the dom.

useEffect(() => {
  const editor = new EditorJs();

  return () => {
    editor.destroy();
  }
}, []);

@ilyamore88 this time my onClickHandler will not work. it stores the output data from editor