Simple Filtering with Craft CMS and Gatsby

Learn how to implement filter functionality by combining Craft CMS data with Gatsby and React hooks.

Mutual
Written by
Mutual
Published 19 Dec 2019
1 min read

A walkthrough of a simple filter UI driven by Craft CMS data, Gatsby, and React hooks.

Fetching data

Start with a GraphQL query that pulls categories and posts from Craft:

{
  craft {
    categories: categories(group: "newsCategories") {
      ... on craft_newsCategories_Category {
        id
        title
        slug
      }
    }
    allPosts: entries(section: "news") {
      ... on craft_news_news_Entry {
        id
        title
        newsCategory {
          slug
        }
      }
    }
  }
}

Building the filter

Use useState to hold the filtered list and the active filter:

const [posts, setPosts] = useState(allPosts)
const [selected, setSelected] = useState("all")

const filterPosts = value => {
  let posts = allPosts
  if (value !== "all") {
    posts = allPosts.filter(post =>
      post.newsCategory.find(category => category.slug === value)
    )
  }
  setSelected(value)
  setPosts(posts)
}

Optional extras

Framer Motion. Wrap the filtered list in AnimatePresence for clean transitions as items enter and leave.

Permalinks. Generate category pages in gatsby-node.js so each filter has its own URL, and apply the filter on mount with useEffect.

Where this pattern fits

Blog archives, product filters, team directories, location search — same shape. For larger result sets, pair it with something like react-paginate.

Sources

Further reading

Craft CMS
Getting the most out of AI with Craft CMS
8 min
Craft CMS
GraphQL vs Element API for headless Craft CMS
6 min
Craft CMS
How To Improve Craft CMS Search Results
7 min

Let's get your site
where it should be

Emma Andrew

Start a conversation with Emma and Andrew

Emma, Operations Director · Andrew, Technical Director

hello@mutual.agency