#Button component with dynamic tag

2 messages · Page 1 of 1 (latest)

echo raptor
#

I want to create a button component that can be used as a button or a (NextJS) link. I think its close to working, but the element Tag is complaining about the passed props as if it doesnt know wich Tag is passed and wich props to use. What am I doing wrong?

import Link, { type LinkProps } from "next/link";

type Props<T extends boolean> = {
  link: T;
} & (T extends true
  ? LinkProps
  : React.ButtonHTMLAttributes<HTMLButtonElement>);

const Button = <T extends boolean>({
  link,
  children,
  ...props
}: React.PropsWithChildren<Props<T>>) => {
  const Tag = link ? Link : "button";

  return (
    <Tag {...props}>
      {children}
    </Tag>
  );
};

export default Button;
echo raptor
#

THis is the error

    ...;
} & React.RefAttributes<...>> | "button"
Type '{ className: string; } & Omit<PropsWithChildren<Props<T>>, "link" | "className" | "size" | "children"> & { children: ReactNode; }' is not assignable to type 'IntrinsicAttributes & Omit<AnchorHTMLAttributes<HTMLAnchorElement>, keyof InternalLinkProps> & ... 4 more ... & ButtonHTMLAttributes<...>'.
  Property 'href' is missing in type '{ className: string; } & Omit<PropsWithChildren<Props<T>>, "link" | "className" | "size" | "children"> & { children: ReactNode; }' but required in type 'InternalLinkProps'.ts(2322)
link.d.ts(11, 5): 'href' is declared here.