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
"Craft Pulse" plugins temporarily removed from Craft Plugin store
1 min
Craft CMS
What site owners should know about Craft CMS 6
5 min
Craft CMS
Do I need to upgrade from Craft 4?
1 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