loading...

Gatsby GraphQL Imports from JSON

jakesweb profile image Jacob Colborn ・3 min read

To see the full code you can check it out on my Github

GitHub logo jakesweb / portfolio

My portfolio website. Created with Gatsby. Deployed with Netlify.

I was working on building my portfolio site. Besides realizing that I do not have nearly enough projects to make a legitimate portfolio site, I also realized that I wanted to be able to add projects to a grid to make a clean layout. Now, I could have just created a Component with all of the individual projects copied and pasted, but I just needed some key data to change per grid item. This sounds like a job for queries! I didn't want a whole database and since it is structured data, that sounded like a job for json!

Gatsby comes with GraphQL builtin. GraphQL is a query language. It can read in from databases, but it can also read from other structured data if loaded correctly. Let's take a look at that first.

To load the data for GraphQL we have to let Gatsby know how to push it over. This was added to my gatsby-config.js file:

`gatsby-transformer-json`,
    {
      resolve: `gatsby-source-filesystem`,
      options: {
        name: `json`,
        path: `${__dirname}/src/json`,
      },
    },

You will need the gatsby-transformer-json NPM package to utilize this. The path is where I stored the json file, inside src/json which I created. The configuration file is what tells Gatsby how to load the file into the parser and allow it to be queried by GraphQL. The json file was just a list of 3 attributes that all of my Project components would need. I named the json file projects.json.

[
  {
    "image": "https://res.cloudinary.com/jakes-web/image/upload/e_outline/v1574999653/portofolio/Pomodoro.png",
    "link": "https://codepen.io/jakesweb/live/awLdxp",
    "title": "Pomodoro Clock"
  }
]

Now, you will want to know how to query this data. GraphQL picks up the file and loads the data in as <Filename>Json so in my case it was ProjectsJson. Being GraphQL it preloads a query for all data from the json named allProjectsJson. This is what we can utilize to pull the data into our Gatsby component. You can see the GraphQL playground by starting your Gatsby development server and then browsing to http://localhost:8000/___graphql.

If you are following along on the Github repository I linked at the top, I created a component to use for styling each project link. This is src/components/ProjectItem.js. I then linked this component over to the Project.js component. The Project component needs to have an import for GraphQL and StaticQuery as such: import { StaticQuery, graphql } from "gatsby" to utilize GraphQL.

From here I created a component to gather a list of Project Items into an array. Now, pausing for a moment of reflection, I could probably do this without a helper function and just run straight into a map function. I will be working that out once I make my personal website look better. StaticQuery is a component that allows us to query the data from GraphQL. This is where we gather the data and lay it out into the getProjectsList helper function.

function getProjectsList(data) {
  const projectsArray = []
  data.allProjectsJson.edges.forEach(item =>
    projectsArray.push(
      <ProjectItem
        image={item.node.image}
        link={item.node.link}
        title={item.node.title}
      />
    )
  )
  return projects Array
}

const Project = ({ children }) => (
  <HeaderDiv>
    <div className="header-div">
      <h1>My Projects</h1>
    </div>
    <StaticQuery
      query={graphql`
        query ProjectItemQuery {
          allProjectsJson {
            edges {
              node {
                image
                link
                title
              }
            }
          }
        }
      `}
      render={data => <ProjectGrid>{getProjectsList(data)}</ProjectGrid>}
    />
  </HeaderDiv>

I know what you are thinking. That is a lot of curled braces, but that's GraphQL for you. The GraphQL query runs a query I called ProjectItemQuery, this runs against a builtin query that is created by GraphQL called allProjectsJson. It is easier to see how the edges and nodes work if you look through the GraphQL local viewer from your Gatsby develop server (which can be found at http://localhost:8000/___graphql, as long as your Gatsby server is using port 8000). From the query, we want to get the data nodes of image, link, and title. The query pushes all the returned information to a variable called data. Taking that, it's passed into the getProjectsList function to lay out the array and render the page.

If you want to see this in practice you can head over to my website. Don't mind the view right now, I am working on getting better as a designer! If you have any thoughts you can let me know in the comments. Thank you for reading!

Posted on by:

jakesweb profile

Jacob Colborn

@jakesweb

Trying to learn javascript and taking everyone on the ride with me.

Discussion

markdown guide