Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

216
Views
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 answers
Answer question

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 Report

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!