Categories
TypeScript Answers

How to add TypeScript types for React checkbox events and handlers?

Spread the love

Sometimes, we want to add TypeScript types for React checkbox events and handlers.

In this article, we’ll look at how to add TypeScript types for React checkbox events and handlers.

How to add TypeScript types for React checkbox events and handlers?

To add TypeScript types for React checkbox events and handlers, we should set the change event object to the React.ChangeEvent<HTMLInputElement> type.

For instance, we write

const Foo = () => {
  const onChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    //...
  };
  return <input type="checkbox" onChange={onChange} />;
};

to add a check with a change event handler.

Then we set the e parameter of onChange to React.ChangeEvent<HTMLInputElement>.

Then we’ll get type checks and autocomplete for the e object.

Conclusion

To add TypeScript types for React checkbox events and handlers, we should set the change event object to the React.ChangeEvent<HTMLInputElement> type.

Leave a Reply

Your email address will not be published.

If you like the content of this blog, subscribe to my email list to get exclusive articles not available to anyone else.