Deno Fresh getting pathname

532 Views Asked by At

I'm quite new to deno and the Fresh framework (which is really hard to google for answers). I wanna make a nav link a different background color of it matches the pathname

this is what I tried:

const NavLink = ({ href, children }: NavLinkProps) => {
  const isActive = location.pathname === href
  const bgClass = isActive ? tw`bg-gray-900` : tw`bg-transparent`

  return (
    <a
      href={href}
      className={tw`px-3 py-2 rounded-md text-sm font-medium text-white ${bgClass}`}
    >
      {children}
    </a>
  )
}

But location is undefined..

2

There are 2 best solutions below

0
On BEST ANSWER

You can get current URL data from PageProps.url and pass it to your component.

From the docs

The PageProps interface actually contains a bunch of useful properties that can be used to customize the rendered output. Next to the matched url pattern parameters, the raw url, and the route name can also be found in here.

const NavLink = ({ href, children, location }: NavLinkProps) => {
  const isActive = location.pathname === href
  const bgClass = isActive ? tw`bg-gray-900` : tw`bg-transparent`

  return (
    <a
      href={href}
      className={tw`px-3 py-2 rounded-md text-sm font-medium text-white ${bgClass}`}
    >
      {children}
    </a>
  )
}

export default function Page(props: PageProps) {
  return (
    <div>You are on the page '{props.url.href}'.
      <NavLink href="/foo" children="Foo" location={props.url} />
    </div>
  )
}
1
On

I think the data-[current] option will be nicer. Also you don't need tw if you have version higher 1.1.

const NavLink = ({ href, children }: NavLinkProps) => {
  return (
    <a
      href={href}
      className="bg-transparent data-[current]:bg-gray-900 px-3 py-2 rounded-md text-sm font-medium text-white"
    >
      {children}
    </a>
  )
}