Skip to content

Cannot use <a> inside link Nextjs #1

@hashirshoaeb

Description

@hashirshoaeb

Hi @tnarla,

I was learning design system from your youtube videos, and I liked your approach of handling link or button dynamically. But I get this error in the following line

let content = <ButtonOrLink {...props} />;

So, I wrote this instead

interface LinkProps extends React.AnchorHTMLAttributes<HTMLAnchorElement> {
  href: string;
}

interface ButtonProps extends React.ButtonHTMLAttributes<HTMLButtonElement> {}

export type Props = LinkProps | ButtonProps;

export function ButtonOrLink(props: Props) {
  if ("href" in props) {
    const { href, children, className, ...rest } = props;
    // https://blog.rampatra.com/how-to-make-an-html-button-element-behave-like-a-link-component-in-next-js
    return (
      <Link href={href} {...rest}>
        <button className={className}>{children}</button>
      </Link>
    );
  } else {
    const { ...rest } = props;
    return <button {...rest} />;
  }
}

would love to have your thoughts on it.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions