There are quite a few ways to get HTML component’s prop types in React. Let’s go through them and use <button>
as an example.
type ButtonProps = React.ComponentPropsWithoutRef<'button'>;
// Example: if you want to override onClick to allow async functions:
type ButtonProps = ComponentPropsWithoutRef<'button'> & {
onClick?: (
event: MouseEvent<HTMLButtonElement, globalThis.MouseEvent>,
) => void | Promise<void>;
};
React.ComponentPropsWithoutRef<'button'>
usually best, forwardRef
not usedReact.ComponentPropsWithRef<'button'>
when building reusable component libraries and forwardRef
is usedReact.ComponentProps<'button'>
same as WithRef above, but better to be specificReact.JSX.IntrinsicElements["button"]
verbose and cannot inline, i.e. first have to define type for the button before getting the propsReact.ButtonHTMLAttributes<HTMLButtonElement>
verbose and must remember correct ButtonHTMLAttributes
for each html element (for list of elements see List of specialized HTML Attributes toggle), same as React.ComponentPropsWithoutRef<'button'>
React.DetailedHTMLProps<React.ButtonHTMLAttributes<HTMLButtonElement>, HTMLButtonElement>
verbose and same as React.ComponentPropsWithRef<'button'>
React.HTMLProps<HTMLButtonElement>
wrong typingsReact.HTMLAttributes<HTMLButtonElement>
wrong typings (div is likely a special case which works)