albertofortes

UI engineer | front-end React developer

JavaScript, #100DaysOfGatsby, Gatsby,

Sorting a GatsbyJS-blog posts list with GraphQL

2019-01-13

Sorting a GatsbyJS-blog posts list with GraphQL

How to sort a list with GraphQL in Gatsby and React.

Problem. We have a list of .md pages to display in a page, and we want to show them in a certain order, usually, date.

To show them, a basic naked-HTML way (forget class-name to styling, SEO on page, accesibility and so on) should be:

1export default ({ data }) => { 2 return ( 3 <div> 4 <p>{data.allMarkdownRemark.totalCount} posts:</p> 5 <div> 6 {data.allMarkdownRemark.edges.map(({ node }) => ( 7 <div key={node.id}> 8 <Link to={node.fields.slug}><img src={node.frontmatter.banner} /></Link> 9 <Link to={node.fields.slug} title={node.frontmatter.title}>{node.frontmatter.title}{" "}</Link> 10 <small>{node.frontmatter.date}</small> 11 <div>{node.excerpt}</div> 12 </div> 13 ))} 14 </div> 15 ) 16}

And the GraphQL query should be:

1export const query = graphql` 2 query { 3 allMarkdownRemark( 4 sort: { 5 fields: [frontmatter___date] 6 order: DESC 7 } 8 ) 9 { 10 totalCount 11 edges { 12 node { 13 id 14 frontmatter { 15 title 16 subtitle 17 date(formatString: "DD MMMM, YYYY") 18 image 19 } 20 fields { 21 slug 22 } 23 excerpt 24 } 25 } 26 } 27 } 28`

Thank you for reading.