Álvaro
Álvaro

Reputation: 2598

'Event' is not assignable to parameter of type 'WheelEvent<Element>'

I am trying to find out what's the correct type for the event on an a window scroll listener, I cannot find any reference to fix this error, I see people just assigning the type any

const handleNavigation = (e: React.WheelEvent) => {
  if (e.deltaY > 0) {
    console.log('scrolling down')
  } else if (e.deltaY < 0) {
    console.log('scrolling up')
  }
}

useEffect(() => {
  window.addEventListener('scroll', e => handleNavigation(e))
  return () => window.removeEventListener('scroll', e => handleNavigation(e))
}, [])

TypeScript errors out on the e parameter on the event listener

`Argument of type 'Event' is not assignable to parameter of type 'WheelEvent<Element>'`

Upvotes: 5

Views: 2776

Answers (3)

Marko
Marko

Reputation: 957

This kinda had me pulling my hair lately so here's the official way, as it currently stands

interface WheelEvent<T = Element> extends MouseEvent<T, NativeWheelEvent> {
    deltaMode: number;
    deltaX: number;
    deltaY: number;
    deltaZ: number;
}

import React, { WheelEvent } from 'react';

const handleWheelEvent = (e: WheelEvent<HTMLDivElement>) => {
    // Do something, e.g. e.deltaY ...
};


<div onWheel={handleWheelEvent}>{/** Some code */}</div>;

source https://felixgerschau.com/react-typescript-onwheel-event-type/

Upvotes: 0

T.J. Crowder
T.J. Crowder

Reputation: 1075337

The problem is that WheelEvent is for the wheel event, not the scroll event. If you want deltaY, you want the wheel event. If you use that, the types work. Here"s an example (with the arrow functions removed per my comment on the question):

const handleNavigation = (e: WheelEvent) => { // *** Declare with the DOM"s `WheelEvent` type (not `React.WheelEvent`)
    if (e.deltaY > 0) {
        console.log("scrolling down");
    } else if (e.deltaY < 0) {
        console.log("scrolling up");
    }  
};

useEffect(() => {
    window.addEventListener("wheel", handleNavigation);                 // *** Use `wheel`
    return () => window.removeEventListener("wheel", handleNavigation); // *** Use `wheel`
}, []);

Upvotes: 5

Alex Chirkin
Alex Chirkin

Reputation: 103

DOM methond window.addEventListener expects a DOM-EventListener

const handleNavigation = (e: Event) => {
   console.log(e.target)
}

Upvotes: 0

Related Questions