Reputation: 1443
I am trying to use the Editor of EditorJS. Everything works fine, except that when I first load the page it initializes two editors at the beginning and keeps appending new editors everytime I reload the page. But they are all inside the <div id='editorjs' />
div. Is there something I am missing?
// react etc. imports
import EditorJS from '@editorjs/editorjs'
const EditorComponent = (props) => {
const [input, setInput] = useState({})
const currentuser = useSelector((state) => state.currentuser)
const editor = new EditorJS({
holderId: 'editorjs',
autofocus: true,
})
const postNews = () => {
// POSTING SUTFF
}
return (
<Grid>
<Grid templateRows='auto min-content' gap={6}>
<div id='editorjs' />
<Button onClick={postNews}>Post news</Button>
</Grid>
</Grid>
)
}
Here is a screenshot from the dom where two editors are added immediately after loading the page.
Upvotes: 6
Views: 2867
Reputation: 1
export const TextEditor = () => {
const isReady = useRef(false);
const config: EditorConfig = {
holder: "textEditor",
data: {
version: "1",
time: Date.now(),
blocks: [],
},
placeholder: "Let's write...",
};
useEffect(() => {
if (!isReady.current) {
new EditorJS(config);
isReady.current = true;
}
}, []);
return <div id="textEditor" />;
};
Upvotes: -1
Reputation: 864
In my case, I have removed <React.StrictMode> </React.StrictMode>
from my main.js file. It worked for me in "react": "^18.2.0"
Upvotes: 0
Reputation: 41
This worked for me. In useEffect()
, I first checked to make sure if the editor is in its default state, (""
), then proceed to create a new instance of EditorJS
, otherwise skip it.
const [editor, setEditor] = useState("")
useEffect(() => {
editor === "" && setEditor( () => new EditorJS({
holder: "editorjs",
logLevel: "VERBOSE",
placeholder: "Any new inspirations today?",
}))
}, [])
Upvotes: 1
Reputation: 1166
The key is to use editor.isReady
which is provided by editorjs. If it is true then EditorJS is already running.
import React, { useEffect } from "react";
import EditorJS from "@editorjs/editorjs";
const Editor = () => {
let editor = { isReady: false };
useEffect(() => {
if (!editor.isReady) {
editor = new EditorJS({
holder: "editorjs",
});
}
}, []);
return (
<main>
<div id="editorjs"></div>
</main>
);
};
export default Editor;
Upvotes: 1
Reputation: 54
Found a simple solution
const <Your Component Name> = () => {
const [editor, setEditor] = useState("");
useEffect(() => {
setEditor(() => new EditorJS(PostEditorConfig()));
}, []);
// .... other components
return (
<div id=editorjs></div>
)}
Upvotes: 1