I want to upload Image in draft js Editor. when i upload image in server then it successfully uploaded in server and get back imageurl. i want to save this url in <img src="" />
src attribute in draft js but it is not work when i InsertImage function call with url then it show error
editorState.getCurrentContent is not a function
if you what is my problem then please tell me
import { Editor } from 'react-draft-wysiwyg';
import 'react-draft-wysiwyg/dist/react-draft-wysiwyg.css';
import { convertToHTML } from 'draft-convert';
const [editorState, setEditorState] = useState(() =>
EditorState.createEmpty()
);
const [convertedContent, setConvertedContent] = useState(null);
const onEditorStateChange = (newEditorState) => {
setEditorState(newEditorState);
};
const blockToHTML = (block) => {
if (block.type === 'code') {
return <code>{block.text}</code>;
}
// Handle other block types if needed
};
const options = {
blockToHTML,
};
// ...
useEffect(() => {
getData();
const html = convertToHTML(options)(editorState.getCurrentContent());
setConvertedContent(html);
}, [editorState]);
const handleImageUpload = async (file) => {
return new Promise((resolve, reject) => {
var reader = new window.FileReader();
reader.onloadend = () => {
const formData = new FormData();
formData.append('image', file);
axios.post('/saveimg', formData)
.then((data) => {
console.log(data);
console.log('Uploaded Data', data);
const { imageLink } = data.data;
console.log(imageLink);
resolve({ data: { link: imageLink } });
insertImage(imageLink);
});
}
reader.readAsDataURL(file);
});
};
const insertImage = (url) => {
const contentState = editorState.getCurrentContent();
const contentStateWithEntity = contentState.createEntity(
'IMAGE',
'IMMUTABLE',
{ src: url }
);
const entityKey = contentStateWithEntity.getLastCreatedEntityKey();
const newEditorState = EditorState.set(editorState, {
currentContent: contentStateWithEntity,
});
const newContentState = AtomicBlockUtils.insertAtomicBlock(
newEditorState.getCurrentContent(),
entityKey,
' '
);
const newEditorStateWithImage = EditorState.createWithContent(
newContentState
);
setEditorState(newEditorStateWithImage);
};
<div class="container-scroller">
<div style={{ border: '1px solid #CCCCCC', minHeight: 300, backgroundColor: "#fff" }}>
<Editor
editorState={editorState}
onEditorStateChange={onEditorStateChange}
toolbarClassName="toolbarClassName"
wrapperClassName="wrapperClassName"
editorClassName="editorClassName"
toolbar={{
image: {
uploadCallback: handleImageUpload,
alt: { present: true, mandatory: false },
},
}}
/>
</div>
</div>