From ae6b958c0bf11c38f902e86f1e13fb015da6af45 Mon Sep 17 00:00:00 2001 From: Jia Hao Date: Fri, 9 Feb 2018 10:47:37 +0800 Subject: [PATCH] Add example component exporting a fragment --- docs/docs/querying-with-graphql.md | 114 ++++++++++++++++++++++++++++- 1 file changed, 111 insertions(+), 3 deletions(-) diff --git a/docs/docs/querying-with-graphql.md b/docs/docs/querying-with-graphql.md index 683a4ac130e63..d590c4447c695 100644 --- a/docs/docs/querying-with-graphql.md +++ b/docs/docs/querying-with-graphql.md @@ -209,11 +209,11 @@ If you wish to define your own fragments for use in your application, you can us For example, I can put all of my helper fragments in `src/fragments/index.js`: -```javascript +```jsx // src/fragments/index.js export const markdownFrontmatterFragment = graphql` - fragment MarkdownFrontmatterFragment on MarkdownRemark { + fragment MarkdownFrontmatter on MarkdownRemark { frontmatter { path title @@ -228,11 +228,119 @@ They can then be used in any GraphQL query after that! ```graphql query PostByPath($path: String!) { markdownRemark(frontmatter: { path: { eq: $path } }) { - ...MarkdownMetadataFragment + ... MarkdownFrontmatter } } ``` +It’s good practice for your helper components to define and export a fragment for the data they need though. For example, on your index page might map over all of your posts to show them in a list. + +```jsx{14-17,31-34} +// src/pages/index.jsx + +import React from "react"; + +export default ({ data }) => { + return ( +
+

+ Index page +

+

{data.allMarkdownRemark.totalCount} Posts

+ {data.allMarkdownRemark.edges.map(({ node }) => ( +
+

+ {node.frontmatter.title}{" "} + — {node.frontmatter.date} +

+
+ ))} +
+ ); +}; + +export const query = graphql` + query IndexQuery { + allMarkdownRemark { + totalCount + edges { + node { + id + frontmatter { + title + date(formatString: "DD MMMM, YYYY") + } + } + } + } + } +`; +``` + +If the index component becomes too large, you might want to refactor it into smaller components. + +```jsx +// src/components/IndexPost.jsx + +import React from "react"; + +export default ({ frontmatter: { title, date }}) => ( +
+

+ {title}{" "} + — {date} +

+
+) + +export const query = graphql` + fragment IndexPostFragment on MarkdownRemark { + frontmatter { + title + date(formatString: "MMMM DD, YYYY") + } + } +`; +``` + +Now, we can use the component together with the exported fragment in our index page. + +```jsx{15} +// src/pages/index.jsx + +import React from "react"; +import IndexPost from "../components/IndexPost"; + +export default ({ data }) => { + return ( +
+

+ Index page +

+

{data.allMarkdownRemark.totalCount} Posts

+ {data.allMarkdownRemark.edges.map(({ node }) => ( +
+ +
+ ))} +
+ ); +}; + +export const query = graphql` + query IndexQuery { + allMarkdownRemark { + totalCount + edges { + node { + ...IndexPostFragment + } + } + } + } +`; +``` + ## Further reading ### Getting started with GraphQL