How to create multiple pages from single json files in Gatsby

后端 未结 1 856
渐次进展
渐次进展 2021-02-02 17:10

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

相关标签:
1条回答
  • 2021-02-02 17:25

    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
          }
        });
      });
    };
    
    0 讨论(0)
提交回复
热议问题