Borislav Hadzhiev
Sun Apr 17 2022·2 min read
Photo by JoelValve
To type the onScroll event of an element in React, set its type to
React.UIEvent<HTMLElement>
. The UIEvent
type is used for onScroll
events
in React. You can access properties on the element, the event is attached to on
the currentTarget
property.
const App = () => { const handleScroll = (event: React.UIEvent<HTMLElement>) => { console.log(event.currentTarget.scrollTop); console.log(event.currentTarget.offsetHeight); }; return ( <div style={{ border: '3px solid black', width: '400px', height: '100px', overflow: 'scroll', }} onScroll={handleScroll} > <p>Content</p> <p>Content</p> <p>Content</p> <p>Content</p> <p>Content</p> <p>Content</p> <p>Content</p> <p>Content</p> <p>Content</p> <p>Content</p> <p>Content</p> </div> ); }; export default App;
We typed the event as React.UIEvent<HTMLElement>
because the
UIEvent type is used for
onScroll
events in React.
However, we could have been more specific when typing the event.
event
parameter in the function.const App = () => { // 👇️ onScroll event is written inline // hover over the `event` parameter with your mouse return ( <div style={{ border: '3px solid black', width: '400px', height: '100px', overflow: 'scroll', }} onScroll={event => console.log(event)} > <p>Content</p> <p>Content</p> <p>Content</p> <p>Content</p> <p>Content</p> <p>Content</p> <p>Content</p> <p>Content</p> <p>Content</p> <p>Content</p> <p>Content</p> </div> ); }; export default App;
event
parameter and it shows me what the type of the event is.TypeScript is able to infer the type of the event when it's written inline.
This is very useful because it works with all events. Simply write a "mock"
implementation of your event handler inline and hover over the event
parameter
to get its type.
Now that we know that the correct type for the onScroll
event is
React.UIEvent<HTMLDivElement, UIEvent>
, we can extract our handler function.
const App = () => { // 👇️ onScroll event is typed correctly now const handleScroll = (event: React.UIEvent<HTMLDivElement, UIEvent>) => { console.log(event.currentTarget.scrollTop); console.log(event.currentTarget.offsetHeight); }; return ( <div style={{ border: '3px solid black', width: '400px', height: '100px', overflow: 'scroll', }} onScroll={handleScroll} > <p>Content</p> <p>Content</p> <p>Content</p> <p>Content</p> <p>Content</p> <p>Content</p> <p>Content</p> <p>Content</p> <p>Content</p> <p>Content</p> <p>Content</p> </div> ); }; export default App;
onScroll
events.As long as you write the event handler function inline and hover over the
event
parameter, TypeScript will be able to infer the event's type.
Notice that we used the currentTarget
property on the event because we want to
access the element that the event listener is attached to.
The target
property on the event
gives us a reference to the element that
triggered the event.