Created
February 17, 2022 06:23
-
-
Save paulonteri/66f221ce0064811afc02a26c4b1343d1 to your computer and use it in GitHub Desktop.
Adding Ckeditor5 to Next JS / React
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import React, { useEffect, useRef, useState } from "react"; | |
function Editor({ onChange, editorLoaded, name, value }) { | |
const editorRef = useRef(); | |
const { CKEditor, ClassicEditor } = editorRef.current || {}; | |
useEffect(() => { | |
editorRef.current = { | |
CKEditor: require("@ckeditor/ckeditor5-react").CKEditor, // v3+ | |
ClassicEditor: require("@ckeditor/ckeditor5-build-classic") | |
}; | |
}, []); | |
return ( | |
<div> | |
{editorLoaded ? ( | |
<CKEditor | |
type="" | |
name={name} | |
editor={ClassicEditor} | |
data={value} | |
onChange={(event, editor) => { | |
const data = editor.getData(); | |
// console.log({ event, editor, data }) | |
onChange(data); | |
}} | |
/> | |
) : ( | |
<div>Editor loading...</div> | |
)} | |
</div> | |
); | |
} | |
export default function App() { | |
const [editorLoaded, setEditorLoaded] = useState(false); | |
const [data, setData] = useState(""); | |
useEffect(() => { | |
setEditorLoaded(true); | |
}, []); | |
return ( | |
<div className="App"> | |
<h1>ckEditor 5</h1> | |
<Editor | |
name="description" | |
onChange={(data) => { | |
setData(data); | |
}} | |
editorLoaded={editorLoaded} | |
/> | |
{JSON.stringify(data)} | |
</div> | |
); | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import React, { useEffect, useRef, useState } from "react"; | |
const RichTextEditor = () => { | |
const editorRef = useRef(); | |
const [editorLoaded, setEditorLoaded] = useState(false); | |
const { CKEditor, ClassicEditor } = editorRef.current || {}; | |
useEffect(() => { | |
editorRef.current = { | |
CKEditor: require("@ckeditor/ckeditor5-react").CKEditor, //Added .CKEditor | |
ClassicEditor: require("@ckeditor/ckeditor5-build-classic") | |
}; | |
setEditorLoaded(true); | |
}, []); | |
const [data, setData] = useState(""); | |
return ( | |
<> | |
{editorLoaded ? ( | |
<> | |
<CKEditor | |
editor={ClassicEditor} | |
data={data} | |
onReady={(editor) => { | |
// You can store the "editor" and use when it is needed. | |
console.log("Editor is ready to use!", editor); | |
}} | |
onChange={(event, editor) => { | |
const data = editor.getData(); | |
setData(data); | |
}} | |
/> | |
{JSON.stringify(data)} | |
</> | |
) : ( | |
<p>Loading...</p> | |
)} | |
</> | |
); | |
}; | |
export default RichTextEditor; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment