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} />
}
This element can be a button, a div element, an image, etc. This article walks you through a couple of different examples of handling the onClick event in a React app that is written in TypeScript. We’ll see the modern features of React like hooks and functional components.
React Event Handlers. In React, the onClick handler allows you to call a function and perform an action when an element is clicked. onClick is the cornerstone of any React app. Click on any of the examples below to see code snippets and common uses: Call a Function After Clicking a Button. Call an Inline Function in an onClick Event Handler.
When we add event handlers in React, we can't use the types that TypeScript includes in the DOM library because React adds a wrapper around these events. Instead, we need to use the type definitions that React provides. In JSX, you can easily see the difference between native and synthetic events by looking at the attribute.
Just like HTML, React can perform actions based on user events. React has the same events as HTML: click, change, mouseover etc. onClick instead of onclick. onClick= {shoot} instead of onClick="shoot ()".
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With