Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 299
Nicolas Avatar asked Dec 23 '22 07:12

Nicolas


1 Answers

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);
}
like image 137
Vladimir Rovensky Avatar answered Dec 25 '22 21:12

Vladimir Rovensky