• This repository has been archived on 30/Dec/2023
  • Stars
    star
    140
  • Rank 261,473 (Top 6 %)
  • Language
    JavaScript
  • License
    MIT License
  • Created over 7 years ago
  • Updated almost 4 years ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

[Deprecated] Super simple way to create dynamic routes with Next.js

Next.js Dynamic Routes

/!\ Deprecated, please don't use

Dynamic routes are now natively supported on Nextjs v9 and higher. This package will stay around on npm, but it is now unmaintained and there will be no new releases.


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.js
server.get('/user/:id', (req, res) => {
  return app.render(req, res, '/user', req.params)
})
// ./pages/index.js
<Link href={`/user?id={id}`} as={`/user/${id}`}><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 = require('nextjs-dynamic-routes')

const router = new Router()

router.add({ name: 'character', pattern: '/characters/:id' })

router.add({ name: 'film', pattern: '/films/:id' })

// if the name of your route is different from your component file name:
router.add({
  name: 'characterAndFilm',
  pattern: '/character-and-film/:characterId/:filmId',
  page: '/character-and-film'
})

module.exports = router

Setup your request handler

const express = require('express')
const next = require('next')
const Router = require('./routes')

const app = next({ dev: process.env.NODE_ENV !== 'production' })
const server = express()
const handle = Router.getRequestHandler(app)

app.prepare()
  .then(() => {
    server.get('*', (req, res) => handle(req, res))
    server.listen(3000)
  })

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.js
import React from 'react'
import { Link } from '../routes'

export default () => (
  <ul>
    <li><Link route="character" id="1"><a>Luke Skywalker</a></Link></li>
    <li><Link route="character" id="2"><a>C-3PO</a></Link></li>
    <li><Link route="film" id="1"><a>A New Hope</a></Link></li>
    <li><Link route="film" id="2"><a>The Empire Strikes Back</a></Link></li>
    <li>
      <Link route="characterAndFilm" characterId="1" filmId="2">
        <a>The Empire Strikes Back and Luke Skywalker</a>
      </Link>
    </li>
  </ul>
)
// pages/character.js
import React from 'react'

export default class Character extends React.Component {
  static async getInitialProps({ query }) {
    return fetch(`//swapi.co/api/films/${query.id}`).then(x => x.json())
  }

  render() {
    return <p>{this.props.name}</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 prefetch route="film" id="2"><a>The Empire Strikes Back</a></Link>

Imperative API

Router.pushRoute(name, params [, options])

import Router from '../routes'

<button onClick={() => Router.pushRoute('film', { id: 2 })}>
  Go to film 2
</button>

Router.replaceRoute(name, params [, options])

import Router from '../routes'

<button onClick={() => Router.replaceRoute('film', { id: 2 })}>
  Go to film 2
</button>

Router.prefetchRoute(name, params)

import Router from '../routes'

<button onClick={() => Router.prefetchRoute('film', { id: 2 })}>
  Prefetch film 2
</button>

Router.getRoutePath(name, params)

import Router from '../routes'

console.log(Router.getRoutePath('characterAndFilm', { characterId: 2, filmId: 5 }))
// => '/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 prefetch route="film" id="2" queryParams={{ utm_campaign: 'website' }}>
  <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.pushRoute('film', {
  id: 2,
  queryParams: {
    utm_campaign: 'website'
  }
})

More Repositories

1

ts-pattern

🎨 The exhaustive Pattern Matching library for TypeScript, with smart type inference.
TypeScript
10,932
star
2

hotscript

A library of composable functions for the type-level! Transform your TypeScript types in any way you want using functions you already know.
TypeScript
3,337
star
3

type-level-typescript-workshop

Interactive exercises to get familiar with TypeScript's most advanced features
TypeScript
228
star
4

evolui

A tiny reactive user interface library, built on top of RxJs.
JavaScript
51
star
5

rx-ease

Spring animation operator for rxjs 🦚✨
TypeScript
21
star
6

use-middleware-reducer

React.useReducer which you can use with the huge middleware ecosystem of Redux.
TypeScript
8
star
7

hetic_formation_react

React introduction for HETIC teammate ;)
JavaScript
3
star
8

immutable-deep-update

Immutably update deeply nested data structures with ease.
JavaScript
3
star
9

vdom-tag

A template literals tag function to build a virtual dom tree
JavaScript
2
star
10

fullscreen.js

native javascript or jquery plugin to set responsive fullscreen size to videos or images
JavaScript
2
star
11

npm-package-starter

A boilerplate to help you get started creating a npm package.
JavaScript
2
star
12

notion-v2

JavaScript
2
star
13

WTFRU

HTML
1
star
14

intro-to-functional-programming

functional programming course (in french)
TypeScript
1
star
15

raytracer-haskell

Haskell
1
star
16

eclosion

Projet Ecriture.
JavaScript
1
star
17

raytracing

C++
1
star
18

rove2

TypeScript
1
star
19

react-state-reducer

intro to the state reducer pattern in react
1
star
20

social-clipboard

JavaScript
1
star
21

react-stack-boilerplate

personnal react stack based on react-transform-boilerplate
JavaScript
1
star
22

react-side-effects

Intro course about using side effects in a react application
1
star
23

block-vdom-test

TypeScript
1
star
24

raytracer-rust

raytracer in one weekend implemented in Rust
Rust
1
star
25

sketchfab-random-avatar

generative design experiment
JavaScript
1
star
26

hetic_formation_es6_laBase

JavaScript
1
star