DEV Community

Cover image for Typescript event types for React
Fateh Mohamed 🐒
Fateh Mohamed 🐒

Posted on

Typescript event types for React

When you migrate your React applications from Javascript to Typescript you want everything to be typed right! and If you start having the type any it means that you are in the wrong direction 😞

Ok cool, you have to create your own types, interfaces... but what about React types, for instance React Events types.
For instance you have a submit event



 const handleSubmit = (event) => {
    event.preventDefault()
    const data = new FormData(event.currentTarget)
    console.log({
      email: data.get('email'),
      password: data.get('password'),
    })
  }


Enter fullscreen mode Exit fullscreen mode

Typescript is complaining and you need to provide a type for your event

Image description

You need to know what type is your event here, but how? πŸ€”
All what you have to do is to write an inline event handler and hover over the event parameter to know that it's of type React.FormEvent<HTMLFormElement> πŸ‘

Image description

Great! Here is your new code and Typescript is happy



const handleSubmit = (event: React.FormEvent<HTMLFormElement>) => {
 ...


Enter fullscreen mode Exit fullscreen mode

Till now everything is good but can't you see that it's a long ugly type 😫 You can make it shorter and nicer.

Let us create a new types file types.ts where we can create new types or in our case only renaming existing ugly ones. Examples bellow



type FormEvent = React.FormEvent<HTMLFormElement>
type MouseEvent = React.MouseEvent<HTMLButtonElement>
type ChangeEvent = React.ChangeEvent<HTMLInputElement>
...

export { FormEvent, MouseEvent, ChangeEvent };


Enter fullscreen mode Exit fullscreen mode

Now our React.FormEvent<HTMLFormElement> type became FormEvent 😎

Again here is how our code will look like now



import { FormEvent } from './types'

const handleSubmit = (event: FormEvent) => {
 ...


Enter fullscreen mode Exit fullscreen mode

Short, Clean and Correct.

Thanks for reading and hope it was helpful

Top comments (0)