Search code examples
reactjstypescripttypescript-typingsonfocus

Use onFocus on a div with React and Typescript


I can not figure out how to use the Focus event with React and Typescript:

private onFocus(event: FocusEvent) {

}

...

<div
  tabIndex={0}
  onFocus={this.onFocus}
>
 Element
</div>

With the code above I get the following error

Types of property 'onFocus' are incompatible.

Type '(event: FocusEvent) => void' is not assignable to type '((event: FocusEvent) => void) | undefined'.

Type '(event: FocusEvent) => void' is not assignable to type '(event: FocusEvent) => void'.

Types of parameters 'event' and 'event' are incompatible.

Type 'FocusEvent' is not assignable to type 'FocusEvent'.

Property 'initFocusEvent' is missing in type 'FocusEvent'.

I tried a bunch of approaches to try to make the Typescript compiler happy but nothing seems to work.


Solution

  • Based on the error it seems like you're using the wrong FocusEvent type - you are handling a React synthetic event, so you need to use the React type.

    I'm getting no errors with the following handler (your results may vary depending on your version of react.d.ts):

    import {FocusEvent} from 'react'
    ...
    private onFocus(ev: FocusEvent<any>){
        console.log(ev);
    }