currently I am working on a project with Next.js and CKEditor 5. I created an Editor-Component which I want to use on a page. Since I need the value of the input on the parent page, I am using a state and setState as props.
My Code looks like this:
Page:
import dynamic from "next/dynamic";
import { useState } from 'react';
export default function Create() {
const Editor = dynamic(() => import("../components/MyEditor"), { ssr: false });
const [text, setText] = useState("")
const handleTextInput = (textInput) => {
setText(textInput)
}
return (
<>
<div key="editor1div">
<Editor key="editor1" handleInput={handleTextInput} data={text} />
</div>
</>
)
}
Editor-Component:
import Editor from '../../ckeditor5-custom-build/build/ckeditor'
import { CKEditor } from '@ckeditor/ckeditor5-react'
import '../../ckeditor5-custom-build/build/translations/de';
const MyEditor = (props) => {
const editorConfiguration = {
toolbar: {
items: ['bold', 'italic', 'underline', '|', 'undo', 'redo'],
}
};
return (
<>
<CKEditor
editor={Editor}
config={editorConfiguration}
data={props.data}
onChange={(event, editor) => {
props.handleInput(editor.getData())
}}
/>
</>
);
}
export default MyEditor
My Problem: The Editor gets rerendered everytime, a key is hit. That means it also loses focus, which leads to a bad user experience. As far as I understand, setting a key to the editor should prevent rerendering on every props change, but it did not work. As suggested in other similar questions, I tried uuid's v4()-Method as key, but also this did not solve the problem.
The solution I wish for: In the best case, the editor would not rerender on every new char that is entered and just stay the same. Alternatively, if that is not possible, I could also work with a solution in which I manually set the focus to the editor or where the state is not permanently updated, but only on a button click on the Page itself.
Did anybody have similar problems or knows a solution?
Kind regards
Robert
I found the solution my self. For everybody with similar problems: the reason is the dynamic import inside the component. If the dynamic import is outside the component, it works:
import dynamic from "next/dynamic";
import { useState } from 'react';
const Editor = dynamic(() => import("../components/MyEditor"), { ssr: false });
export default function Create() {
const [text, setText] = useState("")
const handleTextInput = (textInput) => {
setText(textInput)
}
return (
<>
<div key="editor1div">
<Editor key="editor1" handleInput={handleTextInput} data={text} />
</div>
</>
)
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.