Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

218
Visualizações
how to make a Next.js "Link" 's "href" property optional

I've made the Next.js Link as a custom React function with typescript since the "href" property is required for "Link" to be able to call it anywhere I want . so I couldn't used it as a button which working as a submit button in forms

import NextLink, { LinkProps } from "next/link";
import { HTMLProps, FC } from "react";

export const LinkButton: FC<LinkProps & HTMLProps<HTMLAnchorElement>> = ({
  as,
  children,
  href,
  replace,
  scroll,
  shallow,
  passHref,
  className,
  title,
  onClick,
  ...rest
}) => (
  <NextLink
    as={as}
    href={href}
    passHref={passHref}
    replace={replace}
    scroll={scroll}
    shallow={shallow}
  >
    <a className={className} {...rest}>
      {children || title}
    </a>
  </NextLink>
);

and when I used it in somewhere it gave me this error

<LinkButton onClick={() => alert("hello")} title="Find Events" />

Property 'href' is missing in type '{ onClick: () => void; title: string; }' but required in 
type 'LinkProps'.

how could I make href optional then if it doesn't called I can conditionally add a "" tag except of "" tag

about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

You can omit href property and define as optional:

Omit<LinkProps & HTMLProps<HTMLAnchorElement>, "href"> & { href?: string }

and then inside component props destructuring you need to specify default value

...
href = "",
...
about 4 years ago · Juan Pablo Isaza Relatório

0

In order that href is never empty you can get its route and return it when it is not defined

const router = useRouter()
<NextLink
  as={as}
  href={href ? href : router.asPath} // <---
  passHref={passHref}
  replace={replace}
  scroll={scroll}
  shallow={shallow}
>
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda