Answer the question
In order to leave comments, you need to log in
How to properly handle events in React + Typescript?
Good day to all!
I am working on the function of closing modals by ESC in a React + Typescript project. I encountered
the following problem: when hanging an event handler on an element, TS does not accept the React.KeyBoardEvent type specified as the type of the event parameter in the corresponding function:
const closeByESC = (event: React.KeyboardEvent) => {
if (event.key === "Escape") {
return closePopup();
}
}
...
document.addEventListener('keydown', (event) => {
return closeByESC(event); - ошибка. "Аргумент типа "KeyboardEvent" нельзя назначить параметру типа
"KeyboardEvent<Element>". В типе "KeyboardEvent" отсутствуют следующие свойства из типа
"KeyboardEvent<Element>": locale, nativeEvent, isDefaultPrevented, isPropagationStopped, persist"
})
Answer the question
In order to leave comments, you need to log in
Well, yes.
React.KeyboardEvent
is a synthetic event that is generated in React.
KeyboardEvent
is the original event that is generated in the browser.
KeyboardEvent
lies in event.nativeEvent
u React.KeyboardEvent
.
If you basically don’t care where the event will arrive in the function, and you are only interested in common properties, do this:
const closeByESC = (event: KeyboardEvent | React.KeyboardEvent) => {
document.addEventListener('keydown', closeByESC);
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question