Maradox
Maradox

Reputation: 640

How to get dynamic route path in pages folder in Next.js?

I have a Layout component where I compares routing query and return the layout according to it.

I want to compare dynamic routing, for example invoices/invoice-1

I currently have the following component but as you can see just configArrays.includes(pathname) doesn't work.

const config = {
  layout1: ['/invoices/[id]'],
  layout2: ['/route/sign-in'],
};

const Layout = ({ children }) => {
  const { asPath } = useRouter();
  const url = new Url(asPath, true);
  const pathname = url.pathname;

  if (config.layout1.includes(pathname)) {
    return <Layout1>{children}</Layout1>;
  }

  if (config.layout2.includes(pathname)) {
    return <Layout1>{children}</Layout1>;
  }

  return <DefaultLayout>{children}</DefaultLayout>;
};

Upvotes: 1

Views: 1830

Answers (1)

juliomalves
juliomalves

Reputation: 50378

You can use pathname from useRouter() as it contains the path of the page in /pages, rather than the actual path in the URL. This allows you to match dynamic routes like /invoices/[id].

const Layout = ({ children }) => {
    const { pathname } = useRouter();

    if (config.layout1.includes(pathname)) {
        return <Layout1>{children}</Layout1>;
    }

    if (config.layout2.includes(pathname)) {
        return <Layout2>{children}</Layout2>;
    }

    return <DefaultLayout>{children}</DefaultLayout>;
};

Upvotes: 2

Related Questions