Search code examples
reactjsgatsbyslugstrapi

Is there any way to create dynamic slugs with Gatsby using a template component / page?


I am quite new to Gatsby and I'm wondering if I can create custom routes (slugs) as templates. The use case would be:

  1. Access /articles/name-of-the-article route
  2. Serve component Article.js populated with the information retrieved from an API (i.e Strapi headless CMS) using the name-of-the-article slug.

Solution

  • After some investigations, I found out that there is a much easier way to do so by using gatsby-plugin-create-client-paths. All you need to do is install it with yarn or npm and then in gatsby-config.js you'll add these:

    {
          resolve: `gatsby-plugin-create-client-paths`,
          options: { prefixes: [`/articles/*`] },
    },

    This means that every request slug like this: /articles/the-slug will request the articles.js page and using Link that provided by Gatsby, you can pass props through state prop like this:

    <Link to="/articles/the-slug" state={{ slug: "the-slug", ...etc }}>Anchor Text</Link>

    In this way, src/pages/articles.js becomes the template page for slugs prefixed with /articles.