How to create dynamic routes in Gatsby?

Sometimes, we want to create dynamic routes in Gatsby.

In this article, we’ll look at how to create dynamic routes in Gatsby.

How to create dynamic routes in Gatsby?

To create dynamic routes in Gatsby, we modify the gatsby-node.js file to add routing dynamically.

For instance, we write

gatsbty-node.js

exports.onCreatePage = async ({ page, actions }) => {
  const { createPage } = actions;

  if (page.path.match(/^/app/)) {
    page.matchPath = "/app/*";

    createPage(page);
  }
};

to check if page.path matches the /^/app/ with match.

If it does, we set matchPath to the pattern string to matches on client side.

And then we call createPage with page to update the page.

Then in app.js, we write

import { Router } from "@reach/router";

const SomeSubPage = (props) => {
  return <div>Hi from SubPage with id: {props.id}</div>;
};

const App = () => (
  <Layout>
    <Link to="/app/1">First item</Link>
    <Link to="/app/2">Second item</Link>

    <Router>
      <SomeSubPage path="/app/:id" />
    </Router>
  </Layout>
);

export default App;

to add our routes within Router.

Conclusion

To create dynamic routes in Gatsby, we modify the gatsby-node.js file to add routing dynamically.