The base64 conversion for the image is overflowing from the upload image field in react-draft-wysiwyg

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,

Answer №1

Include props image

toolbar={{
image:{
  "previewImage": true,
  ...,
},
...
}}

Use this code to convert your base64 preview into an image preview

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Developing an animated feature that displays a dynamic count up to the current size of the browser window

I have a script that's able to determine the height and width of my browser window. However, I am facing a challenge in creating a way for these dimensions to count up from zero to their current values upon loading. The desired functionality would be ...

Should we be concerned about the ethics of running javascript that is fetched through an AJAX request?

Currently, I am working on updating an existing web application that allows for user administration and login capabilities. One of the features involves modifying a user's details through a dialog box, where the updated data is then sent to the server ...

button that decreases in size when clicked on

Currently, I am dealing with an element that functions as a button using a combination of Javascript and CSS. To better illustrate the issue, I will simplify the example by removing unnecessary details. The main problem lies in the fact that when this elem ...

Ways to automatically run Java script again when new elements are included in the document model

Recently, I added paging and filtering to a page displaying a list of products. @model ProductFiltersViewModel ... <div class="row"> <aside class="col-3"> <nav class="sidebar card py-2 mb-4"> ...

Add video details to the database using the API

I currently have my own database of YouTube videos which includes the video IDs found in the video links. My goal is to find a way to insert both the title and description of these videos into the database using the YouTube API and MySQL. Although I have ...

How to send data to page component in Next.js using props

Currently, I'm utilizing Next.js with a layout function to incorporate a sidebar on specific pages. export type PageWithLayout<P = {}, IP = P> = NextPage<P, IP> & { withLayout?: (page: ReactElement) => ReactNode; }; Here is an ex ...

What techniques can I use to customize React Bootstrap's css?

Struggling to find a way to override React Bootstrap css without resorting to inline styles. Currently working on rendering an Alert component. https://i.stack.imgur.com/KiATb.png Tried making some CSS modifications, but they're not taking effect du ...

Attempting to open and display the contents of a text file (.txt) within a modal dialog box upon clicking a button

I am attempting to develop a modal that will appear when the user clicks on a specific button. The goal is for this modal to showcase text retrieved from a separate file stored on the server. My aim is to show this text within a dialog box modal. So far, ...

Unable to convert data to a JSON string

I've created a tool for building dynamic tables: <div class="container"> <div class="row"> <div class="col"> <hr> <h3>Add your data</h3> <button id="addTd" type="button" class="btn btn-pr ...

Fixed position toolbar within a container positioned beside a dynamically sized sidebar navigation

I'm trying to figure out how to create a fixed toolbar that fills the remaining width of the page when a side nav is collapsible. Setting the width to 100% causes it to overflow the page due to the dynamic nature of the side nav. Using calc() isn&apos ...

Orbiting ThreeJS object positioned at the coordinates (0,0,0)

I have set up a ThreeJS Scene similar to the image provided. The issue I'm facing is when trying to rotate Obj2 vertically around Obj1, it ends up rotating around the Z axis instead of the center point (0,0,0). My goal is for Obj2 to orbit exclusively ...

Tips on how to properly format a DateTime String

I need help with formatting a DateTime string retrieved from an API where it is in the format of YYYY-MM-DDTHH:MM:SS +08:00 and I want to change it to DD-MM-YY HH:MM getDataFromApi(res) { this.timestamp = this.timestamp.items[0].timestamp; console ...

Switching ng-Idle countdown time from seconds to minutes is possible by adjusting the configuration settings

I have implemented ng-idle in my application, where the warning popup appears after 10 seconds with the message: "Your session will be close in 10 seconds" However, I need to change this to minutes. The session should be closed in 5 minutes instead. How ...

How come my uploaded Excel Javascript add-on opens in an external browser instead of the task pane?

Note: It has come to my attention that I must save the taskpane.html file on my local drive before it opens in an external browser. This detail slipped my notice last week. I am currently developing a Javascript, or rather Typescript, API add-in for Excel ...

I am having trouble locating my TypeScript package that was downloaded from the NPM registry. It seems to be showing as "module not found"

Having some challenges with packaging my TypeScript project that is available on the npm registry. As a newcomer to module packaging for others, it's possible I've made an error somewhere. The following sections in the package.json appear to be ...

Is it possible to attach React Components to Elements without using JSX?

In my React Component, I have the following code: import React, { useEffect } from 'react' import styles from './_PhotoCollage.module.scss' import PhotoCard from '../PhotoCard' const PhotoCollage = ({ author }) => { let ...

`Creating a fluid MySQL table using JavaScript`

One of the challenges I'm facing involves working with a MySQL table that consists of 3 columns: MySQL db table +--+----+-------------+ |id|data|display_order| +--+----+-------------+ |0 |0 |2 | +--+----+-------------+ |1 |1 |1 ...

Error encountered when trying to show a modal using a PHP script

I'm encountering an issue with the modal system on my website. Let me share some code snippets: MODALS ARE BUILT WITH W3.CSS LIBRARY modal.js (including debug statements) let modal = null; let title = null; let content = null; $(document).ready(() = ...

What is the best way to integrate Socket.IO into an Electron application?

I've been looking to incorporate Socket.IO into my Electron application, but the lack of documentation and examples has made it quite challenging. I would greatly appreciate if someone could provide insights on how multiple clients can communicate thr ...

Angular edges on the Material UI table

I noticed that tables in Material-ui have rounded corners by default, but I would like them to have sharp corners instead. After checking out examples on material-ui.com/components/tables/, it seems that the tables use a paper component for styling. The p ...