Simple Filtering with Craft CMS and Gatsby
Learn how to implement filter functionality by combining Craft CMS data with Gatsby and React hooks.
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.