Reputation: 97
i am trying to create a TypeScript Component in React and want to add a custom Drag Start Event. I have the following Code right now:
import React, {RefObject, useEffect, useState} from "react";
type Props = {
id: string,
effect: DataTransfer["dropEffect"],
ref: RefObject<HTMLDivElement>,
onDragStart: any
}
export default function useDrag({id, effect, ref, onDragStart}: Props) {
const [dragState, updateDragState] = useState<string>("draggable");
const dragStart = (event: React.DragEvent<HTMLDivElement>): any => {
updateDragState("dragStart");
event.dataTransfer.dropEffect = effect;
event.dataTransfer.setData("source", id);
onDragStart && onDragStart()
}
useEffect(() => {
const element = ref.current;
if (element) {
element.setAttribute("draggable", String(true));
element.addEventListener("dragstart", dragStart);
return () => {
element.removeEventListener("dragstart", dragStart);
}
}
})
}
But I am always getting the following Error when trying to add the custom Event:
TS2769: No overload matches this call. Overload 1 of 2, '(type: "dragstart", listener: (this: HTMLDivElement, ev: DragEvent) => any, options?: boolean | AddEventListenerOptions | undefined): void', gave the following error. Argument of type '(event: React.DragEvent) => any' is not assignable to parameter of type '(this: HTMLDivElement, ev: DragEvent) => any'. Types of parameters 'event' and 'ev' are incompatible. Type 'DragEvent' is missing the following properties from type 'DragEvent': nativeEvent, isDefaultPrevented, isPropagationStopped, persist Overload 2 of 2, '(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions | undefined): void', gave the following error. Argument of type '(event: React.DragEvent) => any' is not assignable to parameter of type 'EventListenerOrEventListenerObject'. Type '(event: React.DragEvent) => any' is not assignable to type 'EventListener'. Types of parameters 'event' and 'evt' are incompatible. Type 'Event' is missing the following properties from type 'DragEvent': dataTransfer, altKey, button, buttons, and 19 more.
Upvotes: 1
Views: 675
Reputation: 2161
React uses Synthetic Events for callbacks so type of React.DragEvent
is not equal to the type addEventListener
is expecting. Moreover you should not be registering event callbacks with a ref and useEffect, you can implement the drag feature with
<div draggable="true" onDragStart={handleDragStart} />
Upvotes: 0