Search code examples
reactjstypescriptonclickantdreact-typescript

How can get onClick event target value using ant design button react typescript?


I'm currently working on my React and TypeScript project using ant design.
I have button component and I want get button's value and inner text when I click the button.
So here is my code on codesandbox

import { Button, message } from "antd";
import { MouseEvent } from "react";

function App() {
  const buttonClickEvent = (e: MouseEvent<HTMLButtonElement>) => {
    message.info(e.currentTarget.value);
    message.info(e.currentTarget.innerText);
  };
  return (
    <>
      <Button onClick={buttonClickEvent} value="antd">
        antd button
      </Button>
      <br />
      <button type="button" onClick={buttonClickEvent} value="HTML">
        HTML button
      </button>
    </>
  );
}

export default App;

It seems working fine, but type error has occured. Here is the error message.

Type '(e: MouseEvent<HTMLButtonElement>) => void' is not assignable to type 'MouseEventHandler<HTMLAnchorElement> & MouseEventHandler<HTMLButtonElement>'.
  Type '(e: MouseEvent<HTMLButtonElement>) => void' is not assignable to type 'MouseEventHandler<HTMLAnchorElement>'.
    Types of parameters 'e' and 'event' are incompatible.
      Type 'MouseEvent<HTMLAnchorElement, MouseEvent>' is not assignable to type 'MouseEvent<HTMLButtonElement, MouseEvent>'.
        Type 'HTMLAnchorElement' is missing the following properties from type 'HTMLButtonElement': disabled, form, formAction, formEnctype, and 11 more.typescript(2322)

button.d.ts(27, 5): The expected type comes from property 'onClick' which is declared here on type 'IntrinsicAttributes & Partial<{ href: string; target?: string | undefined; onClick?: MouseEventHandler<HTMLAnchorElement> | undefined; } & BaseButtonProps & Omit<...> & { ...; } & Omit<...>> & RefAttributes<...>'

I don't want use any type on button click event. What is the right way get event target's value using ant design button component?


Solution

  • your function returns void. void is not assignable to onClick which expects a function.

    Create a new function that calls fetchData e.g. onClick={(e) => buttonClickEvent(e)}. this solves this error. Link

    after that code will give you another error. at e.currentTarget.value. to solve put (e.currentTarget as HTMLButtonElement).value.