Member-only story
React and TypeScript: Basic Form Event Types
Get away from using "any"
If you are building a form with React and Typescript, you may want to use basic HTML elements instead of a library. If you choose to use basic elements like form
and input
, it’s a good idea to use the correct types when listening to their events. It’s easy to just go with using any
, after all, form
and input
are often the first things people learn in web development. However, it’s a good practice to use the any
type as little as possible.
Below are some useful types that will get you away from the use of any
Basic Form
Here I have a basic form with two functions. One for the form onSubmit
event. Another for the input OnChange
event.
Input OnChange
Getting the value from an input onChange
event is one of the first things people learn when working with HTML. In a Typescript environment, it can be tempting to use any
as a type for the onChange event. Instead of any
, you can useReact.ChangeEvent<HTMLInputElement>
.
const onChange = (event: React.ChangeEvent<HTMLInputElement>) =>
That will give you access to all the values included in the input onChange event.
If you are using a text area and need to differentiate the event, you can use this instead:
const onChange = (event: React.ChangeEvent<HTMLTextAreaElement>) =>
Options Select
Option Select is similar to text input. If you need to do some custom logic with your select, you can use React.ChangeEvent<HTMLSelectElement>
.
const onChange = (event: React.ChangeEvent<HTMLSelectElement>) =>
Form Submission
Similar to onChange
, most developers know that to stop a form from performing its default submission, you make a call to event.preventDefault()
. The type to use for form submissions is React.FormEvent<HTMLFormElement>
const onSubmit = (event: React.FormEvent<HTMLFormElement>) =>
Final View
Getting away from using any
in your function property types is always a good practice. Hopefully these examples help you get away from some easy offenders in your own code.