reactjstypescriptreact-hooks

Creating a Custom Button in React Typescript and add onClick Event


I am trying to create a custom button component in a React Typescript project that use React Hooks and Styled components.

// Button.tsx
import React, { MouseEvent } from "react";
import styled from "styled-components";

export interface IButtonProps {
    children?: React.ReactNode;
    props?: any;
    onClick?:
        | ((event: React.MouseEvent<HTMLButtonElement, MouseEvent>) => void)
        | undefined;
}

const Button: React.FC<IButtonProps> = ({
    children,
    onClick = () => {},
    ...props
}) => {
    const handleOnClick = (e: MouseEvent<HTMLButtonElement>) => {
        onClick(e);
    };
    return (
        <ButtonStyles onClick={handleOnClick} {...props}>
            {children}
        </ButtonStyles>
    );
};

export default Button;

const ButtonStyles = styled.button``;

This is the component I want to use my custom Button

// Login.tsx
import React from "react";
import Button from "../../components/Generic/Button/Button";

const Login: React.FC = () => {
    const clickMe = () => {
        console.log("Button Clicks");
    };

    return (
        <div>
            <Button onClick={clickMe}>My Button</Button>
        </div>
    );
};

export default Login;

I want to click on my custom button and want to print the console log message when I click on it. But I am getting the following error. How to resolve this issue?

Argument of type 'MouseEvent<HTMLButtonElement, MouseEvent>' is not assignable to parameter of type 'MouseEvent<HTMLButtonElement, MouseEvent<Element, MouseEvent>>'.
  Type 'MouseEvent' is missing the following properties from type 'MouseEvent<Element, MouseEvent>': nativeEvent, isDefaultPrevented, isPropagationStopped, persist  TS2345

    16 | }) => {
    17 |    const handleOnClick = (e: MouseEvent<HTMLButtonElement>) => {
  > 18 |        onClick(e);
       |                ^
    19 |    };
    20 |    return (
    21 |        <ButtonStyles onClick={handleOnClick} {...props}>

Solution

  • Your interface IButtonProps defines the expected signature of onClick

        onClick?:
            | ((event: React.MouseEvent<HTMLButtonElement, MouseEvent>) => void)
            | undefined;
    

    However, the e argument to handleClick is defined differently as MouseEvent<HTMLButtonElement>

    If you change the onClick signature to match your handleClick definition, that may go some way to fix it?

        onClick?:
            | ((event: React.MouseEvent<HTMLButtonElement>) => void)
            | undefined;