Learning Next.js: Part 4: Dynamic Routing

Learning Next.js

Next.js is a JavaScript framework based on React for rapidly developing web sites and applications.


Dynamic Routing

Along with providing the <Link> component, Next.js also provides functionality called dynamic routing. Instead of needing to create many files for all possible pages, Next.js allows for creating routes and working with query data to dynamically create pages.

Creating a folder and placing a file with open and closing brackets within its name will route all requests to the internal file, substituting the value inside of the brackets when used.

For example, consider the following structure:


/pages
/post/
/post/[pid].js

Calls to “/post/0”, for example, will route to the file “[pid].js” and send along query data matching “pid”.

import { useRouter } from 'next/router';

const Post = () => {

  const router = useRouter();
  const { pid } = router.query;

  return <p>My Blog Post: {pid}</p>;

}

export default Post;

Using the function useRouter() will return an object with a property containing all values passed to it.

Instead of needing to define multiple pages, then, a single page within a folder creates a route that can respond to data passed to it to dynamically create pages.

Multiple Query Data Entries

Next.js also supports multiple data entries through layered folders. For example, the following structure —


/pages
/p
/p/[pid]
/p/[pid/[comment].js

— would allow code to read both pid and comment from the router.query object.

import { useRouter } from 'next/router';

const Post = () => {

  const router = useRouter();
  const { pid, comment } = router.query;

  return (
    <div>
        <p>My Blog Post ID: {pid}</p>
        <p>Comment: {comment}</p>
    </div>
  );

}

export default Post;

Play with Repl.it Example!

Note: Repl.it example does not work. It is provided for seeing the file and folder structure only.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.