Categories
React Answers

How to add type of the parameter for onKeyPress with TypeScript and React ?

Spread the love

To add type of the parameter for onKeyPress with TypeScript and React, we set the type of the event object to React.KeyboardEvent<FormControl>.

For instance, we write

const handleKeywordKeyPress = (e: React.KeyboardEvent<FormControl>) => {
  if (e.key === "Enter") {
    if (isFormValid()) {
      handleCreateClicked();
    }
  }
};

to set the e parameter to the React.KeyboardEvent<FormControl> type.

Then we can use e.key to check which key is pressed.

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 *