,

Building Pages with JSON in Gatsby Using GraphQL

Posted by






Create Pages with JSON Using Gatsby and GraphQL

How to Create Pages with JSON Using Gatsby and GraphQL

Gatsby is a static site generator built with React and GraphQL. It’s a powerful tool for building fast and efficient websites. One of the key features of Gatsby is its ability to pull in data from various sources, including JSON files, and use that data to create dynamic pages. In this article, we’ll explore how you can create pages with JSON using Gatsby and GraphQL.

Step 1: Set Up Your Gatsby Project

If you haven’t already, you’ll need to set up a Gatsby project. You can do this by running the following command in your terminal:

gatsby new my-website

This will create a new Gatsby project in a directory called “my-website”. Navigate into the directory and start the development server by running:

cd my-website
gatsby develop

Step 2: Create Your JSON Data Source

Next, you’ll need to create a JSON file that contains the data for the pages you want to create. For example, you might create a file called “data.json” with the following content:

  {
    "pages": [
      {
        "title": "Page 1",
        "content": "Lorem ipsum dolor sit amet, consectetur adipiscing elit."
      },
      {
        "title": "Page 2",
        "content": "Praesent ac urna at est vehicula lobortis vel a mauris."
      },
      {
        "title": "Page 3",
        "content": "Duis at libero id elit commodo rhoncus vitae sit amet libero."
      }
    ]
  }
  

Save the file in the “src/data” directory of your Gatsby project.

Step 3: Query the JSON Data with GraphQL

Now that you have your JSON data source set up, you can use GraphQL to query that data in your Gatsby project. Open the “gatsby-node.js” file in the root of your project and add the following code:

  const path = require('path');

  exports.onCreateNode = ({ node, actions }) => {
    const { createNodeField } = actions;

    if (node.internal.type === 'File' && path.extname(node.relativePath) === '.json') {
      const content = require(node.absolutePath);
      content.pages.forEach((page, index) => {
        createNodeField({
          node,
          name: `page_${index}`,
          value: page
        });
      });
    }
  };
  

This code uses Gatsby’s “onCreateNode” API to create fields for each page in the JSON data source.

Step 4: Create Pages from the JSON Data

Finally, you can use the data from your JSON file to create dynamic pages in your Gatsby project. Open the “gatsby-node.js” file again and add the following code:

  exports.createPages = async ({ graphql, actions }) => {
    const { createPage } = actions;
    const result = await graphql(`
      query {
        allFile {
          edges {
            node {
              fields {
                page_0 {
                  title
                  content
                }
              }
            }
          }
        }
      }
    `);

    result.data.allFile.edges.forEach(edge => {
      const page = edge.node.fields.page_0;
      createPage({
        path: page.title.toLowerCase().replace(/ /g, '-'),
        component: path.resolve('src/templates/page.js'),
        context: {
          page
        }
      });
    });
  };
  

This code uses GraphQL to query the data from the JSON file and then uses that data to create a new page in your Gatsby project for each item in the JSON array.

Conclusion

By following these steps, you can create dynamic pages in your Gatsby project using data from a JSON file. This can be a powerful way to manage and display content on your website, and it showcases the flexibility and potential of Gatsby and GraphQL for building modern web applications.


0 0 votes
Article Rating
8 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Paul Salele
1 year ago

Great tutorial!!

dailyshorts
1 year ago

great content brother

SHAHRUKH PINJARI
1 year ago

hi chrish can you please help me how can i create pages in gatsby using fetch api? Because in gatsby-node.js there i'm using createpages in i'm using fetch api call but its not working.

Albino III Cordova
1 year ago

Hi Chris!

Thanks for this great content. So much valuable!

Just a quick question, I placed my data folder inside the src folder and I was able to query the json file.
However, I am not able to utilize the image as childimagesharp, rather when I query, it just response the path.

Here is my path in gatsby-config.js:
path: `${__dirname}/src/data/`

Here is my folder structure:
src/data/projectsData/projectsData.json
src/data/projectsData/images/project1/project1-mobile.jpg

Here is the path of the image inside the "projectsData.json":
"imgMobile": "./projectsData/images/project1/project1-mobile.jpg"

Thanks so much in advance for your help!

Shamil Samaraweera
1 year ago

Thank you very much, Chris. This is the video I was looking past few days. you save lots of time.

Sravan Kumar Yadav
1 year ago

hii bro, can you please tell me how did you get query allMerchJson in localhost:8000/__graphql at the beginning itself. do we have any previous video before this. i'm awaiting your reply

Philip
1 year ago

can u do a part two as to how to view the page with all the products, also the code on the screen is very difficult to read

Shebu
1 year ago

Helpful tutorial!!