diff --git a/docs/docs/querying-with-graphql.md b/docs/docs/querying-with-graphql.md index e762874baa6d4..416ea8b2e7f52 100644 --- a/docs/docs/querying-with-graphql.md +++ b/docs/docs/querying-with-graphql.md @@ -199,6 +199,147 @@ See also the following blog posts: * [Making Website Building Fun](/blog/2017-10-16-making-website-building-fun/) * [Image Optimization Made Easy with Gatsby.js](https://medium.com/@kyle.robert.gill/ridiculously-easy-image-optimization-with-gatsby-js-59d48e15db6e) +## Advanced + +### Fragments + +Notice that in the above example for [querying images](#images), we used `...GatsbyImageSharpResolutions`, which is a GraphQL Fragment, a reusable set of fields for query composition. You can read more about them [here](http://graphql.org/learn/queries/#fragments). + +If you wish to define your own fragments for use in your application, you can use named exports to export them in any Javascript file, and they will be automatically processed by Gatsby for use in your GraphQL queries. + +For example if I put a fragment in a helper component, I can use that fragment in any other query: + +```jsx +// src/components/PostItem.js + +export const markdownFrontmatterFragment = graphql` + fragment MarkdownFrontmatter on MarkdownRemark { + frontmatter { + path + title + date(formatString: "MMMM DD, YYYY") + } + } +`; +``` + +They can then be used in any GraphQL query after that! + +```graphql +query PostByPath($path: String!) { + markdownRemark(frontmatter: { path: { eq: $path } }) { + ...MarkdownFrontmatter + } +} +``` + +It’s good practice for your helper components to define and export a fragment for the data they need. For example, on your index page might map over all of your posts to show them in a list. + +```jsx +// src/pages/index.jsx + +import React from "react"; + +export default ({ data }) => { + return ( +