5

I would like a custom button to optionally receive type attribute:

export interface ButtonProps {
  children: React.ReactNode;
  onClick?: (e: React.MouseEvent<HTMLElement>) => void;
  type: ??
}


export const Button: React.FunctionComponent<ButtonProps> = ({ children, ...buttonProps }) => {
  return <StyledButton {...buttonProps}>{children}</StyledButton>;
};

export default Button;

Same as with 'onClick' which is working. Any type I'm trying to fill in, it still throws an error. What is the correct type for the type attribute?

0

2 Answers 2

15

You can write a button in your editor:

<button type='' />

and probably ctrl/command + click on the type, or hover on the type attribute see its type.

    interface ButtonHTMLAttributes<T> extends HTMLAttributes<T> {
        autoFocus?: boolean | undefined;
        disabled?: boolean | undefined;
        form?: string | undefined;
        formAction?: string | undefined;
        formEncType?: string | undefined;
        formMethod?: string | undefined;
        formNoValidate?: boolean | undefined;
        formTarget?: string | undefined;
        name?: string | undefined;
        type?: 'submit' | 'reset' | 'button' | undefined;
        value?: string | ReadonlyArray<string> | number | undefined;
    }

Also you can extend the props of your component:

export interface ButtonProps extends React.HTMLProps<HTMLButtonElement> {}

You may want to overwrite or omit the types you want.

Sign up to request clarification or add additional context in comments.

1 Comment

If you want just the button type property type without needing to manually write in the enum, you can now key directly into the proptype: type?: React.HTMLProps<HTMLButtonElement>["type"];
0

I looked into element types in React and i found

 button: React.DetailedHTMLProps<React.ButtonHTMLAttributes<HTMLButtonElement>, HTMLButtonElement>;

We can use this React.ButtonHTMLAttributes<HTMLButtonElement>

export type ButtonProps = React.ButtonHTMLAttributes<HTMLButtonElement> & {
  my_custom_types
};

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.