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

Having trouble transmitting JSON data with Durandal JS and Knockout Binding

var newData = { a: ko.observable(), b: ko.observable(), c: ko.observable(), d: ko.observable() }; function setupControlEvents() { $("#save").on("click", handleSave); } function handleSave() { var dataToSen ...

What could be the reason that my JSON request is not functioning properly?

I am currently working on creating a movie search application. This project marks my first time delving into json and I'm facing some issues with my code. As of now, I have it set up and running smoothly on localhost through xampp. On submitting the ...

jQuery opacity transition not functioning properly while all other animations are working fine

I've encountered quite a peculiar issue: Using jQuery v11 on the latest version of Chrome localhost, I can successfully apply jQuery.animate() to various elements and features on my website, including opacity. However, there is one particular element ...

How to iterate through the elements of an object within an array using Vue.js and TypeScript

There was an issue with rendering the form due to a TypeError: Cannot read properties of undefined (reading '0'). This error occurred at line 190 in the code for form1.vue. The error is also caught as a promise rejection. Error Occurred <inpu ...

Draggable HighStock element causing issues with Gridster dragging

I have integrated a stocks chart from HighStocks with gridster, where each gridster block is draggable. However, the stocks time slider gadget can also be dragged and resized. When I move the slider on top of a gridster widget, the entire widget moves alon ...

Error 4 encountered when attempting to upload files using Ajax to a PHP server

On my website, there is a form that looks like this: <form style="width:100%; clear:both; margin-top:50px; background:#fff; border:1px solid green" id="upload_form" enctype="multipart/form-data" class="form" action="" method="post"> <fieldse ...

How can the hreflang tag be used correctly in a React application that supports multiple languages?

I have a React application with 3 pages(routes) and I support 2 languages (English and Spanish). Should I insert the following code into the <head></head> section of the public\index.html file like this? <link rel="alternate" ...

Conceal certain digits of a credit card number in a masked format for security purposes

Is there a reliable method to mask Credit Card numbers in password format within a text field? **** **** **** 1234 If you are aware of a definitive solution, please share it with us. ...

"Using jQuery to enable ajax autocomplete feature with the ability to populate the same

I am encountering a problem with jQuery autocomplete. It works perfectly fine with one textbox, but when I create multiple textboxes using jQuery with the same ID, it only works for the first textbox and not the others. My question is how can I create mult ...

When using useEffect to mimic componentWillUnmount, the updated state is not returned

My goal is to have a functional component with initialized state using useState, which can be updated through an input field. However, upon unmounting the component, I want to log the current state instead of the initial one. In this hypothetical scenario ...

Is it possible to utilize JavaScript to access a .php file located in a separate directory?

Although I have been searching all day, I couldn't find a workout that specifically addresses my issue. I'm new to JavaScript and AJAX. Currently, I am exploring a web app called calendar.php located in the directory C:\xampp\htdocs&bs ...

Express.js response.json method can be used to render both HTML and JSON content in the

I have a router that is sending JSON data to the client as shown below: router.get('/', function(req, res, next) { UserModel.selectAllUsers(function(err, vals){ if(err){ console.log(err); } res.json({d: v ...

The Fusion of Ember.js and Socket.io: Revolutionizing Web

I have been trying to incorporate a basic Ember application into the view of my node application. I have verified that Ember is properly set up and my sockets are functioning correctly. However, I am encountering an issue where the data is not being displa ...

What is the best way to navigate to each specific project within a collection of projects in a gallery?

I am using Next.js to create a gallery of projects where each project can be clicked on to navigate to its individual page. The data file feeds the projects component with information such as image, description, id, etc., including a link to the respective ...

Automatically create CSS properties for left and top using absolute positioning

When looking at these websites as models: On each of them, I noticed that there is a well-organized column of boxes for every post. I attempted to recreate this using various methods, but couldn't achieve the exact layout on my own website. It seems ...

Tips for correctly cloning a table row:

Currently, I am engaged with a Django project that involves incorporating a form within a table structure. <table name="mytable" id="table_purchase" role="grid"> <thead> <tr> <th class="text-center" hidden>No</th& ...

Having trouble getting the JQuery Tipsy tooltip to display correctly with D3.js circles?

Below is the d3.js code that I have used: var circles = vis.selectAll("circle").data(data) circles .enter() .append("svg:circle") .attr("stroke", "black") .attr("cx", function (d) { return xRange(d.year); }) ...

Ways to change the visibility of a view depending on a state in vuex?

If I have a button <Button> Log me in! </Button>, and I want to dynamically change its style based on the state of my Vuex app (state.user is not null). How should I properly implement this functionality? I'm considering creating a field ...

"How can I perform a expressjs database query based on a specific user's

app.get('/user/:id', function(req, res){ fetchData(req.params.id, res); }); function fetchData(id, res) { connection.query('SELECT * FROM data WHERE name = ?' , function(err, rows){ res.render('users', {users ...

What is the best way to disable the click function for <a> tags that have a specific class?

I am dealing with parent navigation items that have children, and I want to prevent the parent items from being clickable. Here is an example of how they currently look: <a href="parent">Parent Item</a> Is there a way to select the <a> ...