drag-and-dropdraftjsdraft-js-plugins

Draft.js insert image at dropped position


I'm trying to drop image from outside of draft-js editor but it's always inserted at last position of the cursor/selection in editor (or at end if cursor/selection not set).

This is my wrap around draft-js-drag-n-drop-plugin

const droppableBlockDndPlugin = {
  ...blockDndPlugin,
  handleDrop: (
    selection,
    dataTransfer,
    isInternal,
    {getEditorState, setEditorState}
  ) => {
    const editorState = getEditorState();
    const raw = dataTransfer.data.getData('text');
    const data = raw ? raw.split(IMAGE_BLOCK_TYPE_SEPARATOR) : [];
    if (data.length > 1 && data[0] === IMAGE_BLOCK_TYPE_PURE) {
      const url = data[1];
      if (url) {
        const newState = imagePlugin.addImage(editorState, url);
        setEditorState(newState);
      }
    }

    return blockDndPlugin.handleDrop(selection, dataTransfer, isInternal, {
      getEditorState,
      setEditorState
    });
  }
};

Basically I'm just doing extra logic before base handleDrop occurs where I insert image using imagePlugin.addImage. Is there way to drop image to dragged position?


Solution

  • Actually it was quite obvious solution - you should just use passed selection and create new state with it and then add image to that new state:

    const newState = imagePlugin.addImage(EditorState.forceSelection(editorState, selection), url);
    setEditorState(newState);