Start trial
Plans & PricingContact Us
Log InStart For Free

How to add drag and drop in your app’s rich text editor

November 24th, 2022

4 min read

an initial image being dropped into the primary image imitation drag and drop

Written by

Joe Robinson

Category

How-to Use TinyMCE

Setting up drag and drop in your app’s rich text editor – whether it’s for a word processing or document building experience – doesn’t have to create maintenance work. It doesn’t have to contribute to your growing list of improvement requests showing on the roadmap.

Building drag and drop functionality can be a quick solution for you and your team. But it can, at the same time, introduce long term maintenance issues. TinyMCE, an enterprise rich text editor, brings with it drag and drop functionality out-of-the-box. It’s a straightforward procedure to configure the editor for specific drag and drop cases. It does not require setting a “draggable” attribute on the texteditor or textbox tags.

The purpose of this article is to provide a demo, showing what’s possible with TinyMCE drag and drop, including error handling.

How to set up and test drag and drop

Testing out drag and drop, in this case, requires a demo. To create the demo, start by getting a FREE API key, which gives you 14 days access to TinyMCE Premium plugins, as well as removing warning messages concerning domain names from the text area.

  1. Navigate to the Get-tiny sign up page to get your FREE API key – you can use your GitHub or Google account to sign in.

Once you have your key ready:

  1. Create an index.html file.

  2. With your file open, in the head section, add script tags, and reference TinyMCE Cloud through a CDN link within the script tags. This is what the link looks like:

<script
  src="https://cdn.tiny.cloud/1/your-api-key/tinymce/6/tinymce.min.js"
  referrerpolicy="origin"
></script>;
  1. Add another pair of script tags, add the following JavaScript. It’s the tinymce.init method, and it’s how you control TinyMCE:

<script>
   tinymce.init({
   selector: "#editor",
   plugins: "powerpaste casechange searchreplace autolink directionality advcode visualblocks visualchars image link media mediaembed codesample table charmap pagebreak nonbreaking anchor tableofcontents insertdatetime advlist lists checklist wordcount tinymcespellchecker editimage help formatpainter permanentpen charmap tinycomments linkchecker emoticons advtable export print autosave",
   toolbar: "undo redo print spellcheckdialog formatpainter | blocks fontfamily fontsize | bold italic underline forecolor backcolor | link image addcomment showcomments  | alignleft aligncenter alignright alignjustify lineheight | checklist bullist numlist indent outdent | removeformat",
   height: '700px'
       });
</script>
  1. Add initial HTML content, and the CSS selector class to some textarea tags. The selector is set as an id with the value “editor” in the TinyMCE init script:

<body>
  <h1>TinyMCE Quick Start Guide</h1>
  <form id="post">
    <textarea id="editor">Hello, World!</textarea>
  </form>
</body>
  1. To see drag and drop working at an essential level with images, change the body HTML content:

    <body>       
        <img src="https://live.staticflickr.com/3514/3990050315_3958b7ea9e_n.jpg" alt="An island with tall mountains">
        <textarea name="" id="editor" cols="30" rows="10">TinyMCE</textarea>
    </body>

Test run the index.html file by opening it in your browser, or use a local server command with Python or with the PHP command:

The drag and drop function working with TinyMCE in a demo

You can see that TinyMCE has drag and drop functionality out-of-the-box. It works well for images, and if you need more information on uploading images with TinyMCE, check on the following articles:

  1. How to get started using image uploads with Bootstrap
  2. Using image upload with Tiny Drive

Drag and drop image upload with React

If your application is running from a framework like React, you can set up TinyMCE as your app’s rich text editor, making use of the TinyMCE React integration.

The following demo shows how drag and drop works with a React demo that uses a variety of content such as headers and hyperlinks, not just an image file. The content is drawn from an example React app, that demonstrates a travel journal created by Mamarmar on GitHub.

  1. On your workstation, create a new React project:

npx create-react-app tinymce-react-dragdrop
  1. Change into the project directory and install the TinyMCE React integration:f

cd tinymce-react-dragdrop
npm install --save @tinymce/tinymce-react
  1. Open the ./src/App.js file using a text editor, and paste in the following configuration:

import React, { useRef } from "react";
import { Editor } from "@tinymce/tinymce-react";
import Destination from "../src/components/destinations";
import data from "..src/components/data";

export default function App() {
  const editorRef = useRef(null);
  const destinations = data.map((destination) => {
    return <Destination key={destination.title} destination={destination} />;
  });

  const log = () => {
    if (editorRef.current) {
      console.log(editorRef.current.getContent());
    }
  };

  return (
    <>
         
      <div>
               {destinations}
           
      </div>
           
      <Editor
        tinymceScriptSrc={process.env.PUBLIC_URL + "/tinymce/tinymce.min.js"}
        onInit={(evt, editor) => (editorRef.current = editor)}
        initialValue="<p>Drag and drop content into the editor.</p>"
        init={{
          height: 500,
          menubar: false,
          plugins: [
            "advlist",
            "autolink",
            "lists",
            "link",
            "image",
            "charmap",
            "anchor",
            "searchreplace",
            "visualblocks",
            "code",
            "fullscreen",
            "insertdatetime",
            "media",
            "table",
            "preview",
            "help",
            "wordcount",
          ],
          toolbar:
            "undo redo | blocks | " +
            "bold italic forecolor | alignleft aligncenter " +
            "alignright alignjustify | bullist numlist outdent indent | " +
            "removeformat | help",
          content_style:
            "body { font-family:Helvetica,Arial,sans-serif; font-size:14px }",
        }}
      />
           <button onClick={log}>Log editor content</button>
         
    </>
  );
}
  1. Inside the src/ folder, create a new folder called components, and change into the directory.

mkdir components/
cd components
  1. Make two new files for including some drag and drop content from the example travel journal app:

touch  destinations.js
touch data.js
  1. Paste the following into the destinations.js file

import React from "react";
function Destination(props) {
  return (
    <div>
           
      <img src={props.destination.imageUrl} />
           
      <div>
               
        <div>
                   
          <a href={props.destination.googleMapsUrl}>
                       Google URL          
          </a>
                 
        </div>
               <h2>{props.destination.title}</h2>
               
        <p>
                   {props.destination.startDate}-{props.destination.endDate}
                 
        </p>
               
        <p>
                   {props.destination.description}
                 
        </p>
             
      </div>
         
    </div>
  );
}

export default Destination;
  1. Paste this content into the data.js file

const data = [
  {
    title: "Island",
    googleMapsUrl: "https://goo.gl/maps/bFgopUF7a2SKmdcf7",
    startDate: "275689",
    description: "An island.",
    imageUrl: "https://live.staticflickr.com/3514/3990050315_3958b7ea9e_n.jpg",
  },
];
export default data;
  1. Save the changes, and then start the React app:

npm run start
  1. When the application loads, test out dragging and dropping different content:

TinyMCE drag and drop working in the browser

TinyMCE’s drag and drop functionality works out of the box for framework integration as well as HTML content.

If drag and drop is not working, there is a solution.

Troubleshooting drag and drop

If you’re finding that drag and drop is not working with images, and is returning errors such as "Dropped file type is not supported", check if you have the image_file_types option, or the block_unsupported_drop option configured in your TinyMCE init script config:

images_file_types: "jpg,svg,webp";
block_unsupported_drop: true;

Drag and drop attempts to add any file formats not included in the file types list are blocked. To enable drag and drop, add any missing file types to the configuration list, or set the unsupported drop option to false.

Troubleshooting drag and drop in React

If you’re finding that TinyMCE in React is blocking drag and drop, and responding with the  "Dropped file type is not supported" , one solution is to set up an event handler that triggers when the onDrop event happens. One drag and drop solution suggested is the following:

  1. In your React demo App.js file, enter the following into the <Editor> component configuration:

<Editor
…
componentWillMount() {
            this.editor.onDrop.subscribe(async () => {
                let event = event;
                //Stops the drag and drop pop up

                event.preventDefault();
                event.stopImmediatePropagation();
                event.stopPropagation();

                let files = event.dataTransfer.files;
                let uploadedFiles = await this.uploadFiles(files); // backend call

                uploadedFiles.forEach(file => {
                    // modify this for different file types
                    this.insertContent(`<img src="${file.Url}" />`);
                })
            })
          }
        }}
      />
  1. Save the changes, and test out the drag and drop again.

Drag and drop functionality changes

Making use of TinyMCE’s file types and the block unsupported drops options are the main methods you can use to configure changes to the TinyMCE drag and drop functionality.

For TinyMCE, drag and drop functionality works out of the box, but if you need any further support, contact us to find out more about how TinyMCE can support your application.

HTMLUse CasesProduct DevelopmentTextarea
byJoe Robinson

Technical and creative writer, editor, and a TinyMCE advocate. An enthusiast for teamwork, open source software projects, and baking. Can often be found puzzling over obscure history, cryptic words, and lucid writing.

Related Articles

  • How-to Use TinyMCEDec 12th, 2024

    Bootstrap Inline Forms: Step-by-Step Instructions | TinyMCE

Join 100,000+ developers who get regular tips & updates from the Tiny team.

This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.

Tiny logo

Stay Connected

SOC2 compliance badge

Products

TinyMCEDriveMoxieManager
© Copyright 2024 Tiny Technologies Inc.

TinyMCE® and Tiny® are registered trademarks of Tiny Technologies, Inc.