I have a problem with react-editor-js library. I'm trying to get data from it, but it doesn't output and when I check instanceRef it's null. Here is the code.
const Create = () => {
const instanceRef = React.useRef(null);
let data = { '1': 'test' }
async function handleSave() {
const savedData = await instanceRef.current.save()
console.log(savedData)
}
return (
<div>
<Header Name='Создание'/>
<Menu/>
<div className="editor">
<ReactEditorJS
instanceRef={(instance) => (instanceRef.current = instance)}
tools={EDITOR_JS_TOOLS}
data={data}
onChange={() => handleSave}
/>
</div>
</div>
);
};
If I use
onChage={() => handleSave}
I get this error.
Uncaught (in promise) TypeError: Cannot read properties of null (reading 'save')
Thanks for your help!
CodePudding user response:
As per ReactEditorJS docs - you should use onInitialize to save your instance on initialize.
So in your case try this -
const Create = () => {
const instanceRef = React.useRef(null);
let data = { '1': 'test' }
async function handleSave() {
const savedData = await instanceRef.current.save()
console.log(savedData)
}
return (
<div>
<Header Name='Создание'/>
<Menu/>
<div className="editor">
<ReactEditorJS
//changed instanceRef to onInitialize
onInitialize={(instance) => (instanceRef.current = instance)}
tools={EDITOR_JS_TOOLS}
data={data}
//need to add '()' to call handleSave
// or you can change it to onChange={handleSave}
onChange={() => handleSave()}
/>
</div>
</div>
);
};
References - How to access editor-js instance?
Note - I have not tried this solution but by reading the documentation I have added this answer, let me know if it does not work.
