Next.js Dynamic Routes
A dynamic routing solution for the awesome Next.js framework.
Why ?
Next.js introduced in it's V2 a programmatic routing API allowing you to serve your Next app from, for example, an express server:
// yourServer.jsserver
// ./pages/index.js<Link = =><a>Visit me!</a></Link>
But as the number of pages grows, it's getting a little hard to manage...
Introducing Dynamic Routes
npm install --save nextjs-dynamic-routes
Setup your routes
Create a routes.js
file and list all your Dynamic routes.
You don't have to list your regular routes, as Next.js will handle them as usual (but you can!).
const Router = const router = router router // if the name of your route is different from your component file name:router moduleexports = router
Setup your request handler
const express = const next = const Router = const app = const server = const handle = Router app
Use your routes
Then Nextjs Dynamic Routes exports a Link
component. It's just like next/link
,
but it adds a route
prop that let you refer to a route by its name.
// pages/index.jsimport React from 'react'import Link from '../routes' <ul> <li><Link ="character" ="1"><a>Luke Skywalker</a></Link></li> <li><Link ="character" ="2"><a>C-3PO</a></Link></li> <li><Link ="film" ="1"><a>A New Hope</a></Link></li> <li><Link ="film" ="2"><a>The Empire Strikes Back</a></Link></li> <li> <Link ="characterAndFilm" ="1" ="2"> <a>The Empire Strikes Back and Luke Skywalker</a> </Link> </li> </ul>
// pages/character.jsimport React from 'react' Component static async { return } { return <p>thispropsname</p> }
Prefetching data
Next.js has this great feature allowing you to prefetch data for your next routes in the background.
You can benefit from that by simply putting a prefetch
property on any Link :
<Link ="film" ="2"><a>The Empire Strikes Back</a></Link>
Imperative API
Router.pushRoute(name, params [, options])
import Router from '../routes' <button => Go to film 2</button>
Router.replaceRoute(name, params [, options])
import Router from '../routes' <button => Go to film 2</button>
Router.prefetchRoute(name, params)
import Router from '../routes' <button => Prefetch film 2</button>
Router.getRoutePath(name, params)
console// => '/character-and-film/2/5'
Query params
The Link component has a queryParams
prop which you can fill with an object of regular query parameters.
<Link ="film" ="2" => <a>The Empire Strikes Back</a></Link>
This will result in the following url: /films/2?utm_campaign=website
.
You can use queryParams
with the imperative API as well
// It doesn't work only for pushRoute, but for all the other methods as well.Router