Categories
React Answers

How to add TypeScript interface signature for the onClick event in React?

Spread the love

Sometimes, we want to add TypeScript interface signature for the onClick event in React.

In this article, we’ll look at how to add TypeScript interface signature for the onClick event in React.

How to add TypeScript interface signature for the onClick event in React?

To add TypeScript interface signature for the onClick event in React, we use the React.MouseEventHandler<HTMLButtonElement> type.

For instance, we write

interface IPropsSquare {
  message: string;
  onClick: React.MouseEventHandler<HTMLButtonElement>;
}

to define the IPropsSquare interface.

In it, we add the onClick property and set it to the React.MouseEventHandler<HTMLButtonElement> type.

Then we can set the onClick prop to a function that’s used as the click event handler for the button without type errors.

Conclusion

To add TypeScript interface signature for the onClick event in React, we use the React.MouseEventHandler<HTMLButtonElement> type.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *