How to load dynamic blog in Gatsby Site

Gatsby
November 12, 20202 minutesuserShailesh Ladumor
How to load dynamic blog in Gatsby Site

We have recently developed a site into the gatsby.

We have a blog site and hosted it on a different domain but now we want to move to one place at our main site. now, we have challenges for displaying dynamic blogs on the gatsby site.

Finally, I found that gatsby provides support to render dynamic blogs as static pages. when build is created that time fetches the blogs from the server and creates a static page for all the blogs.

Gatsby is a very good platform and manages such a kind of thing easily.

So, I will show you how to create static pages from the API response into the Gatsby site.

Here are the steps you need to follow correctly.

Steps 1

Create a one blog file where you want to load a blog in your design.

For an ex. I created a file blog/index.js inside the component directory and the code looks like this,

Steps 2

Open a file gatsby-node.js

Declare the const for the API URL at the beginning of the file.

const blogURL = 'http://blog-api.com/api/posts';

We need to create an instance of the node-fetch for fetching data from the API server.

const fetch = require(`node-fetch`);

Import the path for resolving the page while creating a static page.

const path = require('path');

See the example how to create a static page from APIs. code look's like,

exports.createPages = (async ({graphql, actions}) => {
    const blogs = await fetch(blogURL);
    blogs.data.forEach((blog) => {
        createPage({
            path: 'blog/' + blog.slug,
            component: path.resolve(`./src/components/blog/index.js`),
            context: {
                // Data passed to context is available
                // in page queries as GraphQL variables.
                slug: blog.slug,
                blog: blog,
            },
        })
    })

Now we are done, and you can access the blog page via slug.