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>
.