CMS Posts

How to connect contentful CMS in the gatsby website

Gatsby

Gatsby is a blazing-fast website framework for React. It allows developers to build React-based websites within minutes.

Contentful CMS

Contentful is content infrastructure. Contentful lets you create, manage and distribute content to any platform. Unlike a CMS, Contentful give you total freedom to create your own content model so you can decide which content you want to manage.

Integrate Gatsby with Contentful

Install gatsby-source-contentful package

npm install gatsby-source-contentful

gatsby-config.js file

add the gatsby config file in the following code

plugins: [
    {
        resolve: `gatsby-source-contentful`,
        options: {
            spaceId: `your_space_id`,
            accessToken: `your_access_token`
        }
    }
]

Now connect your gatsby website and contentful CMS.

Here is an example of the GraphQL API query

import React from "react"
import { useStaticQuery, graphql, Link } from "gatsby"
import Layout from "../components/layout"

const Blog = () => {
  const data = useStaticQuery(
    graphql`
      query {
        allContentfulBlogPost{  //BlogPost collection name
          edges {
            node {
              title
              id
              slug
            }
          }
        }
      }
    `
  )
  return (
    <div>
      <p>
        <Link to="/">Go back to the homepage</Link>
      </p>
      <ul className="posts">
        {data.allContentfulBlogPost.edges.map(edge => {
          return (
            <li className="post" key={edge.node.id}>
              <h2>
                <Link to={`/blog/${edge.node.slug}/`}>{edge.node.title}</Link>
              </h2>

              <p className="excerpt">
                {edge.node.excerpt.childMarkdownRemark.excerpt}
              </p>
              <div className="button">
                <Link to={`/blog/${edge.node.slug}/`}>Read More</Link>
              </div>
            </li>
          )
        })}
      </ul>
    </div>
  )
}

export default Blog

Hope this helps.

October 12, 20212 minutesVatsal SakariyaVatsal Sakariya