Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create multiple pages from single json files in Gatsby

I am new to node.js and react but I love gatsby.js. I have followed all the tutorials that I can find and it's such a great tool.

However one of the main reasons why I want to use it is I have a file json with 1000 different records in and I would like to generate a new page for each record.

I believe I have come to the conclusion that I need to learn more about the gatsby-node.js file and am aware of the following resource but are there any tutorials or other examples on this topic that maybe a little easier to follow:

https://www.gatsbyjs.org/docs/creating-and-modifying-pages/#creating-pages-in-gatsby-nodejs

like image 817
Richard Petersen-Hall Avatar asked Feb 06 '18 21:02

Richard Petersen-Hall


1 Answers

The example you were referring to should already give you a good idea. The basic concept is to import the JSON file, loop over it and run createPage for each of the items in your JSON source. So given an example source file like:

pages.json

[{
  "page": "name-1"
}, {
  "page": "name-2"
}]

You can then use the Node API to create pages for each:

gatsby-node.js

const path = require('path');
const data = require('./pages.json');

exports.createPages = ({ boundActionCreators }) => {
  const { createPage } = boundActionCreators;

  // Your component that should be rendered for every item in JSON.
  const template = path.resolve(`src/template.js`);

  // Create pages for each JSON entry.
  data.forEach(({ page }) => {
    const path = page;

    createPage({
      path,
      component: template,

      // Send additional data to page from JSON (or query inside template)
      context: {
        path
      }
    });
  });
};
like image 117
Fabian Schultz Avatar answered Nov 16 '22 20:11

Fabian Schultz