Last updated: Feb 29, 2024
Reading time·3 min
Use the React.FocusEvent<HTMLElement>
type to type the onFocus and onBlur
events in React. The FocusEvent
interface is used for onFocus
and onBlur
events.
import React from 'react'; const App = () => { const handleFocus = (event: React.FocusEvent<HTMLElement>) => { console.log(event); }; const handleBlur = (event: React.FocusEvent<HTMLElement>) => { console.log(event); }; return ( <div> <input type="text" id="message" name="message" defaultValue="" onFocus={handleFocus} onBlur={handleBlur} /> </div> ); }; export default App;
We typed the events as React.FocusEvent<HTMLElement>
because the
FocusEvent type is used for
onFocus
and onBlur
events in React.
However, we could have been more specific when typing the event.
The easiest way for you to find out what the type of an event is, is to write
the event handler inline and hover over the event
parameter in the function.
const App = () => { // 👇️ events are written inline // hover over the `event` parameter with your mouse return ( <div> <input type="text" id="message" name="message" defaultValue="" onFocus={event => console.log(event)} onBlur={event => console.log(event)} /> </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 onFocus
and onBlur
events in
the example is React.FocusEvent<HTMLInputElement, Element>
, we can extract our
handler function.
import React from 'react'; const App = () => { const handleFocus = ( event: React.FocusEvent<HTMLInputElement, Element>, ) => { console.log(event); }; const handleBlur = ( event: React.FocusEvent<HTMLInputElement, Element>, ) => { console.log(event); }; return ( <div> <input type="text" id="message" name="message" defaultValue="" onFocus={handleFocus} onBlur={handleBlur} /> </div> ); }; export default App;
The type we passed to the FocusEvent
generic is HTMLInputElement
because we
attached the events to an input element, however, you could be attaching the
event to a different element.
HTML***Element
. Once you start typing HTML..
, your IDE should be able to help you with autocomplete.Some commonly used types are: HTMLInputElement
, HTMLButtonElement
,
HTMLAnchorElement
, HTMLImageElement
, HTMLTextAreaElement
,
HTMLSelectElement
, etc.
onFocus
and onBlur
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.
If you need to check if an element is focused in React, click on the following article.
You can learn more about the related topics by checking out the following tutorials: