Simple Filtering with Craft CMS and Gatsby

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

M
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
Craft CMS 5.10: Safer Deletes, Time Zones, and an Important Security Fix
4 min
Craft CMS
Why use Craft CMS instead of WordPress?
9 min
Analytics
Privacy-First Analytics, Built Into Your CMS
3 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