Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.
like image 954
Mihai Moraru Avatar asked Jan 25 '23 12:01

Mihai Moraru


1 Answers

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.

like image 71
Mihai Moraru Avatar answered Feb 06 '23 21:02

Mihai Moraru