How to create & use GraphQL fragments in Gatsby
A step by step tutorial on creating and using reusable GraphQL page query fragments with GatsbyJS.
The following tutorial builds off our Open Source starter project and walks you through how to create and use reusable frontend GraphQL fragments in GatsbyJS.
We recommend downloading our Open Source project, checking out the tutorial/backend-fragments branch and carrying out the steps outlined below. All relevant changes can be found on the tutorial/frontend-fragments branch.
git clone git@github.com:delasign/gatsbyjs-typescript-starter.git
Step One: Create the Fragment
In the src create a new folder called fragments and within it create a new file called seo.js and paste in the code found below.
Please note that unlike backend queries, they must fall under a and include a type. You cannot simply state the fragment includes metaTitle and metaDescription. It will not work.
Step Two: Integrate fragment into a query
GraphQL fragments do not need to be imported. To integrate them into a query follow the paradigm ...FragmentName.
Step Three: Verify
Run yarn start to confirm that the page generation algorithm succeeds.
Once complete, navigate to a webpage generated by Gatsby to see your results.
Any Questions ?
We are actively looking for feedback on how to improve this resource. Please send us a note to inquiries@delasign.com with any thoughts or feedback you may have.