What is the method for obtaining a dynamic route path within the pages directory in Next.js?

In my code, I have a special Layout component that compares routing queries and displays the appropriate layout based on the query.

I'm looking to extend this functionality to handle dynamic routing scenarios, such as invoices/invoice-1.

Currently, I have a component set up with different layouts specified in a config object. However, simply using configArrays.includes(pathname) isn't providing the desired results.

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

Answer №1

Instead of using the actual path in the URL, you can utilize the pathname property from the useRouter() hook as it contains the page's path within the /pages directory. This feature allows you to handle dynamic routes such as /invoices/[id].

const CustomLayout = ({ 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>;
};

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Delivering resources through the Nuxt configuration file

https://i.stack.imgur.com/2OWdE.png I came across a bootstrap template online that I want to customize for my Nuxt project. I have stored all the bootstrap files in the static folder. Within the nuxt.config.js file: module.exports = { /* ** Headers ...

Using Angular to retrieve JSON data from a static file

Currently, I am attempting to implement this AngularJS example from a tutorial on Login Tutorial Example. Instead of storing the username and password as simple strings, I am trying to retrieve them from a local file. I understand that this may not be the ...

Tips for extracting CSS data with Selenium webdriver's executescript function

Just starting to learn Javascript in a Node environment... I'm trying to use the code snippet below to extract CSS values for a specific web element, but I'm having trouble parsing it in JavaScript. driver.executeScript(script, ele).then(p ...

Preserve data across all pages using sessions

On my website, I have a pagination system where each page displays 10 data entries. Whenever a user clicks on the pagination buttons, it triggers a request to the database to fetch the corresponding records. Each data entry also includes a button that can ...

"What is the best way to have a data toggle in Vue that waits for the success or failure of

How can I ensure that the modal is triggered only after a successful axios response, without altering any existing styles? The current code triggers the modal before waiting for the axios response, despite adding v-if. Current code: <template> <d ...

Struggling to make a basic JavaScript prompt function as expected

<html> <title>UniqueTitle</title> <head> <link rel="stylesheet" type="text/css" href="style.css" > <script type="text/javascript"> function modifyDates() { var dates = pr ...

Updating a value using jQuery AJAX techniques

Using jQuery AJAX, I am loading the content of a page in this way: $(document).ready(function(){ $('#next').click(function(event){ $.ajax({ url: "load.php?start="+$('#lastid').text(), success: function(html){ $("#results"). ...

Error: Cloudant encountered a problem processing your request

Why is my attempt to upload JSON objects into a Cloudant database resulting in a "400 bad request" error? pos = { 'lat': position.coords.latitude, 'long' : position.coords.longitude }; $.ajax({ type: "POST", ...

Trouble with setting up custom static route

Greetings! I am currently working on setting up my project in React and here is my current project structure: -public --w ---dist ----bundle.js ---index.html -server --server.js -src --app.js -webpack.config.js -package.json -.babelrc For my server, I am ...

What is the best way to calculate the number of squares required to completely fill a browser window in real-time?

I am creating a unique design with colorful squares to cover the entire browser window (for example, 20px by 20px repeated both horizontally and vertically). Each square corresponds to one of 100 different colors, which links to a relevant blog post about ...

How do I execute a Next.js script that utilizes `fs` and `sharp` during development with Webpack?

I'm working on creating a basic GIFPlayer that displays a GIF when the play button is clicked, and shows a PNG otherwise: <img className="w-full h-full" src={isPlaying ? gifPath : imgPath} alt={pic.alt} /> Since I only have a GIF file ...

Issue encountered when attempting to install React modules

Attempted to install sass-loader, as well as node-sass using both yarn and npm; however, encountered identical errors. Various methods were tried: yarn add <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="057664767628696a646160 ...

How to use the handleChange() function in React with various state properties

Explaining a bit about the handleChange function, which takes the name of the state element to be associated with it. Is there a specific reason why it has to be structured like this: handleInputChange(property) { return e => { this.setSta ...

When a page is changed, the Vue.js Active Menu color remains enabled

Check out my website at . I want to customize the navigation bar so that only the active page's navbar li is colored in red. <div class="navigation-items"> <ul class="nav-list"> <li class="nav-item"><nuxt-link to="/en" ...

Grunt Pokes at XML to Set a Variable Destination Name

When using grunt-xmlpoke to update an XML file, the path of the XML file is provided as a parameter. The issue arises when the first WebConfigPath (key) in the files section is interpreted as a string. This results in updating a local copy of the XML fil ...

ways to invoke javascript function on body loading

I'm struggling to invoke a JavaScript function when the body loads. Currently, I have the function call on a button but cannot get it to work when added to the body load event. HTML: <body onload="bodyload();"> JavaScript: function bodyload( ...

Store the beginning and ending times in a MySQL database using Sequelize and Node.js

I am currently developing a project management application where I need to keep track of the start and stop time for user work. To achieve this, I have implemented two buttons in the UI - START and STOP. When a user clicks the START button, the following ...

Is there a way to retrieve a raw value from the API response that matches the one shown in POSTMAN, but my attempts have been unsuccessful?

Looking for some assistance with fetching data from a front-end (React) to the raw value in JSON. Specifically, I'm having trouble with the login functionality. When I input my email and password, the response should match what I see in POSTMAN, but i ...

How can I remove a specific page from the file structure of my NextJS 13 app?

Here is my folder structure: app/view-all/layout.js app/view-all/page.js app/view-all/[itemId] app/view-all/clothes app/view-all/accessories app/view-all/bags All of these components need to utilize an Aside component that I have coded in app/view-all/lay ...

Export nested objects from an AngularJS JSON array to a CSV file

When I download my data into a CSV file, the display setting is showing as "[object Object]". This is not the desired outcome. https://i.stack.imgur.com/ej2UO.png The expected display should look like this: https://i.stack.imgur.com/8JJ88.png This is p ...