Home > database >  How to define the type of a button in react / typescript?
How to define the type of a button in react / typescript?

Time:09-01

I'm currently trying to define the type of a button component, it's currently set as any so it's working, but what would be the real type of this property ?

import React, { Dispatch, SetStateAction } from "react";

interface ButtonI {
  className?: string;
  label?: string;
  children: React.ReactNode;
  type?: any;
  onClick?: Dispatch<SetStateAction<boolean>>;
}

const Button: React.FC<ButtonI> = (props) => {
  return (
    <button
      className={`${props.className}`}
      type={props.type || "button"}
      aria-label={props.label || ""}
      onClick={() => (props.onClick ? props.onClick(true) : null)}
    >
      {props.children}
    </button>
  );
};

export default React.memo(Button);

CodePudding user response:

The type of a button type is

React.ButtonHTMLAttributes<HTMLButtonElement>["type"]

Usage:

type?: React.ButtonHTMLAttributes<HTMLButtonElement>["type"]

it accepts:

"button" | "reset" | "submit" | undefined
  • Related