Answers for "next get current route"

3

router nextjs

import { useRouter } from 'next/router'

function ActiveLink({ children, href }) {
  const router = useRouter()

  const handleClick = (e) => {
    e.preventDefault()
    router.push(href)
  }

  return (
    <a href={href} onClick={handleClick} style={style}>
      {children}
    </a>
  )
}

export default ActiveLink
Posted by: Guest on November-16-2020
0

nextjs router get complete url

function getFullUrl(req, fallback) {
  //server side request object(req)
  if(req) {
    return req.protocol + '://' + req.get('host') + req.originalUrl
    
  } //making sure we are on the client side
  else if(!(typeof window === 'undefined')) {
    return window.location.href
    
  } else {
    return fallback
  }
}

//usage on nextjs
static async getInitialProps({req}) {
   let fullUrl = getFullUrl(req, "")//gets the full url or fallback to ""
    return { fullUrl: fullUrl }
}
Posted by: Guest on January-29-2021
0

get cuurent route name nextjs

import React from 'react'
import Link from 'next/link'
import { useRouter } from 'next/router'

const menu = [
  { title: 'Home', path: '/home' },
  { title: 'Explore', path: '/explore' },
  { title: 'Notifications', path: '/notifications' },
]

const Sidebar = () => {
  const router = useRouter()

  return (
    <div>
      {menu.map((item, index) => {
        return (
          <Link key={index} href={item.path}>
            <a
              className={`cursor-pointer ${
                router.pathname === item.path
                  ? 'text-blue-500'
                  : 'hover:bg-gray-900 hover:text-blue-500'
              }`}
            >
              {item.title}
            </a>
          </Link>
        )
      })}
    </div>
  )
}

export default Sidebar
Posted by: Guest on October-23-2021

Code answers related to "Javascript"

Browse Popular Code Answers by Language