Иво Стратев
Иво Стратев

Reputation: 415

import Event Types from React (TypeScript)

How to import Event Types from React?

For an example how to import KeyboardEvent so it can be used for onKeyDown callback type annotation?

I have browsed Material-ui .d.ts file and found that in that file EventTypes are used as defined in React

onKeyDown?: React.KeyboardEventHandler;

And in React .d.ts

type KeyboardEventHandler = EventHandler<KeyboardEvent>;

But I can't find a way to use import them ...

Upvotes: 21

Views: 31418

Answers (3)

Damian Green
Damian Green

Reputation: 7505

If you receive error "KeyboardEvent requires type argument" with React 16.1+ you can do:

private onKeyDown = (event: React.KeyboardEvent<HTMLInputElement>) => {
   ... 
}

where the generic arg is the type of your element.

Upvotes: 2

farrellw
farrellw

Reputation: 1420

Add KeyboardEvent to your react import statement. Then, in your handler you can use the KeyboardEvent type. If you don't specify it in the import statement, you will use ES5 declaration of KeyBoardEvent, which won't compile with your react project.

import React, { Component, KeyboardEvent } from "react";

export class MyInput extends Component{
...

  handleKeyDown(e: KeyboardEvent<HTMLInputElement>) {
    console.log(e);
    // Do something here
  }

  render() {
      return (
        <input onKeyDown={this.handleKeyDown.bind(this}/>
      );
    }
  }
}

Upvotes: 10

Ser
Ser

Reputation: 2890

It's works fine for me:

handleKeyPress (event: React.KeyboardEvent): any {
}

And I use material-ui too

Upvotes: 41

Related Questions