Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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} />
}
like image 208
Taghi Khavari Avatar asked Jan 15 '20 14:01

Taghi Khavari


People also ask

What is onClick event in react?

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.

How do you call a function in react event handler?

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.

Why can't I use typescript event handlers in react?

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.

How to perform actions based on user events in react?

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 ()".


2 Answers

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.

like image 82
Calin Vlasin Avatar answered Oct 06 '22 19:10

Calin Vlasin


If you create a <button> and hover over onClick prop you'll get the type in the tooltip:

enter image description here

In your example code, you are creating a custom button so the types depend on the implementation of that component.

like image 23
marzelin Avatar answered Oct 06 '22 18:10

marzelin