'What is the correct type for React Click Event?
I want to use a type for my event handler instead of using type any, Can anyone help me with this,please? here is the code I'm trying to refactor:
const MyComponent = () => {
const handleBtnClick = (e: any) => {
e.stopPropagation();
//**Some Code**
}
return <CustomButton onClick={handleBtnClick} />
}
Solution 1:[1]
If you create a <button>
and hover over onClick
prop you'll get the type in the tooltip:
In your example code, you are creating a custom button so the types depend on the implementation of that component.
Solution 2:[2]
For typings you should have TypeScript where you can do this:
const handleBtnClick = (e: React.MouseEvent<HTMLButtonElement>) => { ... }
Please refer to this: https://fettblog.eu/typescript-react/events/
Of course, you could try it without TypeScript but is not worth it.
Hope it helps.
Solution 3:[3]
This seems like a reasonable explanation: https://rjzaworski.com/2018/10/typescript-event-handlers
React.MouseEvent
Solution 4:[4]
I believe the type you are looking for is React.MouseEvent, a synthetic event provided by React. More info and examples may be found here.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | marzelin |
Solution 2 | Olivier Tassinari |
Solution 3 | TKoL |
Solution 4 | jack.benson |