I have a functional react-draft-wysiwyg editor application that allows me to add images. However, I am currently encountering an issue which is detailed below:
https://i.stack.imgur.com/HTjAc.png
This is the code snippet of what I have attempted so far. Even when passing truncatedUrl inside callback for display purposes, the error message "Invalid URL passed" persists.
My goal is to display a small string within the "File Upload" box but pass the complete image URL when clicking on "Add".
Here's my current implementation:
import { Editor } from "react-draft-wysiwyg";
import { EditorState, ContentState } from "draft-js";
import "react-draft-wysiwyg/dist/react-draft-wysiwyg.css";
const [editorState, setEditorState] = useState(EditorState.createEmpty())
useEffect(() => {
let html = stateToHTML(editorState.getCurrentContent())
setContent(html)
}, [editorState])
const handleEditorChange = (state) => {
setEditorState(state);
const selectedBlock = state.getCurrentContent().getBlockForKey(
state.getSelection().getStartKey()
);
const selectedEntity = selectedBlock.getEntityAt(
state.getSelection().getStartOffset()
);
if (selectedEntity !== null) {
if (typeof selectedEntity.getData === 'function') {
const image = selectedEntity.getData().url;
setImageFile(image);
} else {
console.error('selectedEntity does not have getData method');
}
} else {
setImageFile(null);
}
};
const addLesson = async () => {
setIsUploading(true);
try {
const formData = new FormData();
formData.append('name', title);
formData.append('content_type', contentType);
if (contentType === 'text' && content) {
formData.append('content', content);
}
if (contentType === 'video' && video) {
formData.append('content', video);
}
formData.append('course_id', course_id);
formData.append("imageFile", imageFile);
const response = await axios.post(url() + 'api/admin/lessons', formData);
if (response?.status === 200) {
setSuccess('Lesson successfully added.');
window.setTimeout(() => {
history.push(`/course/${course_id}/lessons`);
}, 1000);
}
} catch (error) {
console.error(error);
setError(error?.response?.data?.msg);
}
setIsUploading(false);
};
return (
<div className="row m-3">
<h6 className="edit-box-label ml-2">Lesson Content</h6>
<div className="col-xl-12">
<Editor
editorState={editorState}
onEditorStateChange={handleEditorChange}
toolbar={{
image: {
uploadCallback: (file) => {
return new Promise((resolve, reject) => {
const reader = new FileReader();
reader.readAsDataURL(file);
reader.onload = () => {
const dataURL = reader.result;
const truncatedDataURL = dataURL.substring(10, 30) + "...";
resolve({ data: { link: dataURL } , link : { url : truncatedDataURL} });
};
reader.onerror = (error) => {
reject(error);
};
});
},
alt: { present: true, mandatory: false }
}
}}
/>
</div>
</div>
)
I would greatly appreciate any assistance with this issue. Thank you for your help.
Best regards,