Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to define a home link with conditional logic

I am trying to figure out how to define a home link that renders one page if there is an authenticated user and another if there is not.

Me is my function to check if there is an authenticated user. It works across my application so far.

When I try:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

<HomeLink
            href={!me?  "/" | "/dash"}
           
          >
            <Logo />
          </HomeLink>

I get an error that says:

Type ‘boolean’ is not assignable to type ‘string’.ts(2322)
Nav.tsx(147, 3): The expected type comes from property ‘href’ which is
declared here on type ‘IntrinsicAttributes & HomeLinkProps’

My HomeLinkProps are defined as:

interface HomeLinkProps extends LinkProps {
  href: string
}

function HomeLink({ href, ...props }: HomeLinkProps) {
  const { asPath } = useRouter()
  const isActive = asPath === href

  return (
    <NextLink passHref href={href}>
      <Link
        px={4}
        py={2}
        textDecor="none !important"
       
        {...props}
      >
        {props.children}
      </Link>
    </NextLink>

I think it is correctly defined as a string – both of the alternatives in the href condition are strings – but I dont know how to express that in the Logo field.

How can I add a condition to check for an authenticated user before making the home link direct to one page or another?

>Solution :

See Conditional (ternary) operator.

There should be a colon (:) after the expression that should be executed if the condition is truthy. (Not |)

href={!me ? "/" : "/dash"} or href={me ? "dash" : "/"}

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading