Gatsby dynamic route with multiple parameters

Viewed 1589

I am trying to get gatsby to work with dynamic routes with multiple url parameters. I want to be able to navigate to:

.../items/124/MyItemsTitle

In my gatsby-node.js i have the following code:

exports.onCreatePage = async ({ page, actions }) => {
    const { createPage } = actions;
    // page.matchPath is a special key that's used for matching pages
    // only on the client.
    if (page.path.match(/^\/user/)) {
        page.matchPath = "/user/*";
        // Update the page.
        createPage(page);
    }

    if (page.path.match(/^\/items\/([0-9]+)\/\w+$/)) {
        page.matchPath = "/items/:itemId/:itemTitle";
        // Update the page.
        createPage(page);
    }
};

The component for the router is as follows:

items.js

   <Router>
            <ItemDetail path="/items/:itemId/:itemTitle" />
        </Router>

But it just renders out to the 404

I have tried every type of regex available read through the docs multiple times, but always end up with only one variable in the url. then it works. The soon as I use multiple parameters, it breaks.

Thanks!

1 Answers

Found the issue:

Adding this to gatsby-node.js was enough

if (page.path.match(/^\/items/)) {
    page.matchPath = "/items/*";
    // Update the page.
    createPage(page);
}

And the rest of the path is handled by the router. So the more parameters you want, just add them to the path of your component in the router.

 <Router>
        <Items path="/items/:itemId" />
        <ItemDetail path="/items/:itemId/:itemTitle" />
 </Router>

And this worked for me.

Related