Skip to content

Bug <Button as="a"> onClick handler expects the wrong type #6941

@jdufresne

Description

@jdufresne

When a Button component is rendered as an anchor element, I expect the onClick to be typed for an anchor element, but it remains typed for a button.

Given the component:

import React from 'react';
import Button from 'react-bootstrap/Button';

function MyButton(): React.JSX.Element {
  function handleClick(event: React.MouseEvent<HTMLAnchorElement>): void {
    console.log(event);
  }

  return (
    <>
      <Button as="a" href="/about" onClick={handleClick}>Button</Button>
      <a href="/about" onClick={handleClick}>Anchor</a>
    </>
  );
}

export default MyButton;

I expect no type errors. Instead I get:

test.tsx:11:36 - error TS2322: Type '(event: MouseEvent<HTMLAnchorElement, MouseEvent>) => void' is not assignable to type 'MouseEventHandler<HTMLButtonElement>'.
  Types of parameters 'event' and 'event' are incompatible.
    Type 'MouseEvent<HTMLButtonElement, MouseEvent>' is not assignable to type 'MouseEvent<HTMLAnchorElement, MouseEvent>'.
      Type 'HTMLButtonElement' is missing the following properties from type 'HTMLAnchorElement': charset, coords, download, hreflang, and 19 more.

11       <Button as="a" href="https://github.com/about" onClick={handleClick}>Button</Button>
                                      ~~~~~~~

  node_modules/@types/react/index.d.ts:2281:9
    2281         onClick?: MouseEventHandler<T> | undefined;
                 ~~~~~~~
    The expected type comes from property 'onClick' which is declared here on type 'IntrinsicAttributes & Omit<DetailedHTMLProps<AnchorHTMLAttributes<HTMLAnchorElement>, HTMLAnchorElement>, BsPrefixProps<...> & ButtonProps> & BsPrefixProps<...> & ButtonProps & { ...; }'


Found 1 error in test.tsx:11

react-bootstrap: 2.10.10

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions