Note: This article was last updated on December 19, 2019 and may contain outdated information.
This article demonstrates implementing filter functionality by combining Craft CMS data with Gatsby and React hooks.
Fetching Data
The tutorial begins by querying categories and posts via GraphQL from Craft CMS:
{
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
Using React’s State Hook, the implementation creates filtering logic:
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 Enhancements
Animation with Framer Motion: The guide demonstrates wrapping filtered results in AnimatePresence for smooth transitions during state updates.
Permalinks: Create pre-filtered pages using gatsby-node.js to generate category-specific URLs that auto-filter on load via the Effect Hook.
Broader Applications
This pattern applies to various content types: blog archives, product filters, team directories, and location searches. For larger datasets, pagination libraries like react-paginate can manage result volumes.