Borislav Hadzhiev
Wed Apr 21 2021·2 min read
Photo by Marc Szeglat
Updated - Wed Apr 21 2021
The easiest way to add typings to react events is to use inline callbacks for your events:
import {useState} from 'react'; export const EventsDemo: React.FunctionComponent = () => { const [name, setName] = useState(''); return ( <div> <input onChange={e => setName(e.target.value)} /> <h3>{name}</h3> </div> ); };
If you hover over the even in the input
element you would see that it's of
type React.ChangeEvent<HTMLInputElement>
.
However it's not always an option to define your event handlers inline, so how do you get the type that you need in the particular scenario?
The easiest way would be to hover over the onChange
prop defined on the
input
element, you would then get something like:
(JSX attribute) React.InputHTMLAttributes<HTMLInputElement>.onChange?: ((event: React.ChangeEvent<HTMLInputElement>) => void) | undefined
Notice in the above line - the event is already typed as
React.ChangeEvent<HTMLInputElement>
, all you would have to do is copy paste it
in your handler like so:
import {useState} from 'react'; export const EventsDemo: React.FunctionComponent = () => { const [name, setName] = useState(''); const handleChange = (e: React.ChangeEvent<HTMLInputElement>) => { setName(e.target.value); }; return ( <div> <input onChange={handleChange} /> <h3>{name}</h3> </div> ); };
We have many different types of events whe working with React, you can see the
typescript file definition if you ctrl click on an onChange
or onSubmit
prop
for example. By hovering on any of them you get the type information you need
when defining your own handlers, for example - handleSubmit:
import {useState} from 'react'; export const EventsDemo: React.FunctionComponent = () => { const [name, setName] = useState(''); const handleChange = (e: React.ChangeEvent<HTMLInputElement>) => { setName(e.target.value); }; const handleSubmit = (e: React.FormEvent<HTMLFormElement>) => { console.log('event is', e); }; return ( <div> <form onSubmit={handleSubmit}> <input onChange={handleChange} /> <button type="submit">Submit</button> </form> <h3>{name}</h3> </div> ); };
When you hover over the onSubmit
prop you get:
(JSX attribute) React.DOMAttributes<HTMLFormElement>.onSubmit?: ((event: React.FormEvent<HTMLFormElement>) => void) | undefined
All you then have to do is extract the information that you need from the prop definition - copy paste the event type and you're done.
Using the type inference system indirectly to grab the necessary types helps a ton and saves us time from digging in type definition files or documentation.