Home > Blockchain >  What is the right type for my onClick event here?
What is the right type for my onClick event here?

Time:09-30

What is the right type for my onClick event here?

Live demo: demo live

interface BtnItem {
  label: string;
  onClick?: (id: string) => void;
}

interface DataProps {
  id: string;
  buttons: BtnItem[];
}

const DataButton: React.FC<{
  button: BtnItem;
  onClick?: (event: React.MouseEvent<HTMLElement>) => void;
}> = ({ button, onClick }) => {
  return (
    <div onClick={onClick}>
      <div>{button.label}</div>
    </div>
  );
};

const Data: React.FC<DataProps> = ({ id, buttons }) => {
  return (
    <>
      <h1> What is the problem here? </h1>
      {buttons.map((button) => (
        <DataButton button={button} onClick={button.onClick} />
      ))}
      ;
    </>
  );
};

export default Data;

I am getting the following error:

Type '((id: string) => void) | undefined' is not assignable to type '((event: MouseEvent<HTMLElement, MouseEvent>) => void) | undefined'.
  Type '(id: string) => void' is not assignable to type '(event: MouseEvent<HTMLElement, MouseEvent>) => void'.
    Types of parameters 'id' and 'event' are incompatible.
      Type 'MouseEvent<HTMLElement, MouseEvent>' is not assignable to type 'string'.ts(2322)

CodePudding user response:

The error tells you what type it's looking for:

(event: MouseEvent<HTMLElement, MouseEvent>) => void

So the interface would be:

interface BtnItem {
  label: string;
  onClick?: (event: MouseEvent<HTMLElement, MouseEvent>) => void;
}

Alternatively, if you want to keep the same interface, you'd need to pass a string instead of the whole event object. For example:

onClick={() => button.onClick && button.onClick(id)}

Basically, at its simplest what's happening is the function on the interface in your code is expecting a string but the onClick event sends a MouseEvent<HTMLElement, MouseEvent>. So either the function needs to expect that type, or when calling the function you need to send the type it expects.

  • Related