skip to Main Content

I have a Nextjs application. The app will grow to a nice size (200 pages)

What is the best way to manage links. Some pages will have navigation buttons and and hrefs, hyperlinks.

I am looking for solution to manage

Example: pages -> about, contact, support, home, blog. But when you have 200 pages and you are hardcoding <a href="/about"> </a> if I delete or change the about page name I have to go in all 200 pages and update this

2

Answers


  1. Navigate with click :

    import { useRouter } from "next/router";
    //...
    const router = useRouter()
    <button
    onClick={() => {
    router.push('/url')
    }}
    >Navigate</button>
    

    Navigate with Link :

    import Link from 'next/link';
    //...
    <Link href="/url">Navigate</Link>
    

    And if you have 200 url you should make 200 links you cannot optimize that, but you can create a file for all your link then import it everywhere and when you have to update one path you do it inside this file :

    import Link from "next/link";
    export const HomeLink = () => {
      return <Link href="/">Navigate To Home</Link>;
    };
    export const SettingsLink= () => {
      return <Link href="/settings">Navigate To Settings</Link>;
    };
    //...
    

    and from the file in which you want to navigate :

    import { HomeLink, SettingsLink } from "../your_path";
    //...
    <HomeLink />
    <SettingsLink/>
    
    Login or Signup to reply.
  2. I create a routes file with all my hard-coded routes and use the const throughout my app. I use trailing slash, so they need to be appended to all routes.

    This setup works well for me, and I’ve used it on numerous projects with hundreds of routes. It saved a lot of time over the years when inevitably, I needed to change a route’s href or name.


    My routes file is similar to this:

    export const ROUTE_HOME = {
      href: "/",
      name: "Home",
    };
    export const ROUTE_ABOUT = {
      href: "/about/",
      name: "About",
    };
    

    I use them like

    import Link from 'next/link';
    import {ROUTE_HOME, ROUTE_ABOUT} from 'your/path/to/routes';
    
    <Link href={ROUTE_HOME}>{ROUTE_HOME.name}</Link>
    <Link href={ROUTE_ABOUT}>{ROUTE_ABOUT.name}</Link>
    

    On larger projects, I break the routes out into separate files.

    src > const > routes.ts // top-level routes
    src > modules > auth > const > routes.ts // only auth routes
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search