Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create type for component based on props passed [duplicate]

I'm creating a component that looks like this:

<Button component='a' href='/'>
  Link
</Button>

I want to get the type definition of the component prop, so I can automatically include it in the props for the Button component. Any ideas on what the interface/type for the Button component should look like

like image 449
Oluwakorede Fashokun Avatar asked May 28 '26 13:05

Oluwakorede Fashokun


1 Answers

I've used this pattern before. Declare the component prop of type React.ComponentType<T> | string. Your Button component should look a bit like this:

export interface ButtonProps {
  component?: React.ComponentType<any>; // or React.ReactElement<any>["type"]
  href?: string;
  children?: React.ReactNode;
}

export function Button(props: ButtonProps) {
  const {
    component: Component = "button", // note: uppercase
    children,
    ...other
  } = props;

  return (
    <Component {...other}>
      {children}
    </Component>
  );
}
like image 169
p.s.w.g Avatar answered May 31 '26 10:05

p.s.w.g



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!