😎 Discover cool tips and tricks for customization in our next Developer Deep Dive virtual event - sign up now!

How to Filter Posts by Category Name in Next.js?

3 replies
Last updated: Jun 23, 2021
How to filter posts by schema name “category” using GROQ in next.js? Usually I have to use a query to load my data. But how do you dynamically change the query on filter?
Jun 22, 2021, 1:27 PM
Assuming your category is a reference & you have the category’s
_id
, you can use a variable, either with groq:

fetch(`*[_type == 'post' && references($catId)]`, { catId: 'persian' })
or just string query:


const catId = 'persian'

fetch(`*[_type == 'post' && references(${catId})]`)
if you have multiple categories, you may also do something like this


fetch(`*[_type == 'post' && references(*[_id in $categories]._id)]`, { categories: ['persian', 'bobtail', 'maine_coon'] })
Jun 22, 2021, 3:16 PM
user G
so the categories: can also be a const with array of categories pulled from sanity and filter and map the content with hooks right?
Jun 22, 2021, 11:21 PM
Yes that's right, you would get the array of categories from another fetch
Jun 23, 2021, 12:22 AM

Sanity– build remarkable experiences at scale

Sanity is a modern headless CMS that treats content as data to power your digital business. Free to get started, and pay-as-you-go on all plans.

Was this answer helpful?