Search code examples
graphqlgatsbyghost-blog

Trouble understanding how graphql data is getting to react component


I'm not sure how the react component is getting data from graphql in this library (or in general). I'm looking at https://github.com/TryGhost/gatsby-starter-ghost and in places like src/templates/post.js there is a graph query at the bottom that some how passes the data into the component.

I've looked all around the web for documentation about this but I can't seem to find any.


Solution

  • The simplified process (some steps obviously left out) is pretty much to create a slug that populates data on a template you develop. More information can be found here:

    https://www.gatsbyjs.org/tutorial/part-seven/

    Example:

    import React from "react"
    import { graphql } from "gatsby"
    import Layout from "../components/layout"
    export default ({ data }) => {
      const post = data.markdownRemark
      return (
        <Layout>
          <div>
            <h1>{post.frontmatter.title}</h1>
            <div dangerouslySetInnerHTML={{ __html: post.html }} />
          </div>
        </Layout>
      )
    }
    export const query = graphql`
      query($slug: String!) {
        markdownRemark(fields: { slug: { eq: $slug } }) {
          html
          frontmatter {
            title
          }
        }
      }
    `
    

    The query is at the bottom. It looks for the slug then gets the related GraphQL information and populates it on the template "post.js" as an example.