BLOG // May 5, 2021

Getting random articles in Gatsby

There is no real way in GraphQL to select a random number of articles, whether you are using the local filesystem or something like a Strapi or Contentful backend. You can, however, achieve a somewhat similar affect with pure JavaScript if you have all the content loaded.

Lets say you had a recent article footer on a blog post, that showed the latest 3 articles. It might look something like this:

{data.allStrapiArticles.edges.slice(0, 3).map(document => {
  return (
    <RelatedArticle key={document.node.id} node={document.node} />
  )
})}

You can see there we are taking a slice (0, 4) to get first 3 articles and pass them to our RelatedArticle component.

You could alternatively get a random selection of articles, with this trick:

{data.allStrapiArticles.edges.splice(Math.floor(Math.random()*data.allStrapiArticles.edges.length), 3).map(document => {
  return (
    <RelatedArticle key={document.node.id} node={document.node} />
  )
})}

In specific the trick we are using is to get a random selection of items from a JavaScript map. The plain version of this would be:

x.splice(Math.floor(Math.random()*x.length), 3).map()

Anyway, that'll grab you 3 randomly selected articles from your content.

Comments

Subscribe to new articles

If you enjoy my content, consider subscribing. You will only receive new blog stories, no other email.