NextJs and dynamic routes - how to handle the empty parameter scenario?
Asked Answered
L

1

10

I'm trying to retrieve the url parameter without using query strings, for example, http://localhost:3000/test/1, this is what I have so far:

Dir structure

test
 - [pageNumber].jsx

index.jsx

import React from 'react';
import { useRouter } from 'next/router';

const Index = () => {
  const router = useRouter();

  return (
    <>
      <h1>Page number: {router.query.pageNumber}</h1>
    </>
  );
};

export default Index;

It works, but if I omit the pageNumber param, all I got is a 404 page, an issue we don't have on using query strings.

Now, the question: is it possible to sort this without creating an additional index.jsx page and duplicating code to handle the empty parameter scenario?

Laresa answered 14/6, 2020 at 14:41 Comment(5)
Make a pages/test/index.jsx import and export this from all sub pagesCornhusk
@Cornhusk As easy as it gets. Thank you!Laresa
@Cornhusk can you be more specific? I did not quite get the option you are mentioning and would like to know how it compares to the Optional catch all routesRecor
@Recor Added answer.Cornhusk
@Cornhusk neat!! Cheers :)Recor
C
8

I see I may as well answer this as I got notified of MikeMajaras comment.

There are several ways of doing this, say you have a route that gets posts from a user and shows 10 posts per pages so there is pagination.

You could use an optional catch all route by creating pages/posts/[[...slug]].js and get the route parameters in the following way:

const [user=DEFAULT_USER,page=DEFAULT_PAGE] = context?.query?.slug || [];

"Disadvantage" is that pages/posts/user/1/nonexisting doesn't return a 404.

You could create pages/posts/index.js that implements all code and pages/posts/[user]/index.js and pages/posts/[user]/[page]/index.js that just export from pages/posts/index.js

export { default, getServerSideProps } from '../index';

You get the query parameters with:

const {user=DEFAULT_USER,page=DEFAULT_PAGE} = context.query;

You could also just only create pages/posts/[user]/[page]/index.js and implement all code in that one and config a redirect

module.exports = {
  async redirects() {
    return [
      {
        source: '/posts',
        destination: `/posts/DEFAULT_USER`,
        permanent: true,
      },
      {
        source: '/posts/:user',
        destination: `/posts/:user/DEFAULT_PAGE`,
        permanent: true,
      },
    ];
  },
};
Cornhusk answered 10/3, 2021 at 10:20 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.