1

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>;
};

1 Answer 1

2

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>;
};
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks Julio. It prints out /invoices/[id] as expected.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.