Home > Net >  How to define a home link with conditional logic
How to define a home link with conditional logic

Time:11-10

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:

<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?

CodePudding user response:

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" : "/"}

  • Related