Filter articles by category
Objectives
Section titled โObjectivesโOur news index page is looking great, but itโs missing one key feature: the ability to filter articles by category.
If you try clicking between the different news categories, youโll notice that the URL and page title changes, but the articles donโt update:

In this guide, weโll update the loader function in our app/routes/news.$category.tsx file to filter articles by category and if they are published or not.
Revisiting the loader function
Section titled โRevisiting the loader functionโAt the moment, our loader function is fetching all articles from the database:
export async function loader({ params }: LoaderFunctionArgs) { const { category } = params
invariant(typeof category === 'string', 'Category not found') const categoryTitle = toTitleCase(category)
const allArticles = await prisma.article.findMany({ select: { id: true, title: true, category: { select: { name: true } }, images: { select: { objectKey: true } }, }, })
return data({ categoryTitle, allArticles })}Letโs fix this so that only articles in the specified category are retrieved.
Filtering queries with Prismaโs where option
Section titled โFiltering queries with Prismaโs where optionโ-
Open the
app/routes/news.$category.tsxfile. -
Letโs start by renaming
allArticlesto something more suitable:app/routes/news.$category.tsx export async function loader({ params }: LoaderFunctionArgs) {const { category } = paramsinvariant(typeof category === 'string', 'Category not found')const allArticles = await prisma.article.findMany({const filteredArticles = await prisma.article.findMany({select: {id: true,title: true,category: { select: { name: true } },images: { select: { objectKey: true } },},})return data({ category, allArticles })return data({ category, filteredArticles })} -
Next, we need to actually implement the filtering logic.
Weโll use Prismaโs
whereoption to filter articles bycategory. -
Filter articles by
Section titled โFilter articles by categoryโcategoryWe already have access to the
categoryparameter, so letโs add awhereoption to our query:app/routes/news.$category.tsx export async function loader({ params }: LoaderFunctionArgs) {const { category } = paramsinvariant(typeof category === 'string', 'Category not found')const categoryTitle = toTitleCase(category)const filteredArticles = await prisma.article.findMany({where: {category: {slug: category, // Retrieves only articles in the specified category},},select: {id: true,title: true,category: { select: { name: true } },images: { select: { objectKey: true } },},})return data({ categoryTitle, filteredArticles })} -
Update
Section titled โUpdate useLoaderData with filteredArticlesโuseLoaderDatawithfilteredArticlesFinally, we need to update the
useLoaderDatahook in ourNewsIndexPagecomponent to return thefilteredArticlesdata, andmapthrough this in place of the oldallArticlesarray:app/routes/news.$category.tsx export default function NewsCategoryPage() {const { category, filteredArticles } = useLoaderData<typeof loader>()return (<div className="container py-8 lg:py-16"><h2 className="mb-16 text-h2">{category}</h2><div className="grid grid-cols-1 gap-6 md:grid-cols-4 xl:grid-cols-3">{filteredArticles.map(article => {return (<ArticleCardkey={article.id}title={article.title}categoryTitle={categoryTitle}objectKey={article.images[0]?.objectKey}/>)})}</div></div>)} -
Check filters in the browser
Section titled โCheck filters in the browserโNow, if you navigate to the news index page and click on a category, you should see the articles update based on the selected category:

Summary
Section titled โSummaryโIn this guide, we have:
- Learned about the
whereoption in Prisma to filter database records based on specific criteria. - Updated the
loaderfunction in ourapp/routes/news.$category.tsxfile to filter articles by category and if they are published or not. - Updated the
useLoaderDatahook in ourNewsIndexPagecomponent to return thefilteredArticlesdata and map through this in place of the oldallArticlesarray. - Checked the filters in the browser to ensure they are working as expected.
- Further enhanced the news index page.
Whatโs next?
Section titled โWhatโs next?โIn the next guide, we will add an extra page to display the content of individual articles.