Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Gatsby and Graphql - How to filter allMarkdownRemark by folder

I'm using Gatsby and MarkdownRemark.

I want to query the markdown files and then filter them down to the files contained within a sub-directory. My folder structure looks like this:

- src
 - pages
   -index.md
   -about.md
   - team
    - team_member_1.md
    - team_member_2.md
    - team_member_3.md

So far I can query all the markdown pages in the directory but I'm having trouble trying to filter down path. There must be a way to do it with a graphQL query.

Instead what I do is map all the results and then check if the slug string includes 'team' this tells me that its in the 'team' folder. And then it makes the component.

import React from 'react'
import { useStaticQuery, graphql } from 'gatsby'
import TeamMember from '../components/TeamMember.js'
const Team = () => {
  const data = useStaticQuery(graphql`
    query {
      allMarkdownRemark {
        edges {
          node {
            fields{
              slug
            }
            frontmatter {
              name
              position
              image
            }
          }
        }
      }
    }
  `)

  return (
    <div>
      {data.allMarkdownRemark.edges.map( (item, index) => {
        if(item.node.fields.slug.includes('team')){
          return <TeamMember key={`team_member_${index}`}{...item.node.frontmatter}/>
        }
      } )}
    </div>
  )
}
export default Team

This works fine. But I thought the whole point of graphQl is to query and filter to return the exact data I need. Instead I'm back at writing my own filter code in javascript:

if(item.node.fields.slug.includes('team'))

Is there a Gatsby plugin or a way to filter a query to contain items in a folder?

like image 658
PAT-O-MATION Avatar asked Sep 19 '19 18:09

PAT-O-MATION


2 Answers

@ksav's answer works but it is important to note that regex: "/(team)/" also matches C:\user\gatsby\src\team2\other.md.

So I recommend using allMarkdownRemark(filter: {fileAbsolutePath: {regex: "/(/team/)/" }}) { instead.

like image 197
Vyk Avatar answered Nov 11 '22 20:11

Vyk


Have a look at the gatsby graphql reference for filter and make sure you are using graphiql to explore what is available within your schema.

query MyQuery {
  allMarkdownRemark(filter: {fileAbsolutePath: {regex: "/(team)/"  }}) {
    nodes {
      id
    }
  }
}
like image 24
ksav Avatar answered Nov 11 '22 21:11

ksav