1.0.5 • Published 5 years ago

@fabiodesousa/gatsby-theme-contentful v1.0.5

Weekly downloads
-
License
MIT
Repository
-
Last release
5 years ago

A simple Contentful config theme for Gatsby

  • Simple config for using Contentful with Gatsby, including Preview API for dev environments
  • Simple component for rendering Contentful Rich Text fields

Quick Start

mkdir my-site
cd my-site
yarn init
# install gatsby-theme-contentful and its dependencies
yarn add gatsby react react-dom gatsby-theme-contentful

Then add the theme to your gatsby-config.js.

In your env vars, add your Contentful space id, access token (delivery api token for production, and preview api token for development), and host name (cdn.contentful.com for production, preview.contentful.com for development).

Learn about environment variables: https://gatsby.app/env-vars

require("dotenv").config({
  path: `.env.${process.env.NODE_ENV}`,
})

module.exports = {
  plugins: [
    {
      resolve: `gatsby-theme-contentful`,
      options: {
        spaceId: process.env.CONTENTFUL_SPACE_ID,
        accessToken: process.env.CONTENTFUL_ACCESS_TOKEN,
        host: process.env.CONTENTFUL_HOST
      }
    }
  ],
}

ContentfulRichText Component

  • This component takes in a single parameter, richTextJSON, which is an object returned from Contentful for richtext fields.
  • The component then renders a React component from that JSON object using the documentToReactComponents function of @contentful/rich-text-react-renderer
  • This transformation also allows custom rendering for specific types within the rich text field (e.g. a hyperlink). In its current form, this component makes the following transformations:
    • Replaces new line breaks (made by hitting shift + enter) with a <br /> element
    • Makes hyperlinks open in a new tab (with rel='noopener noreferrer' for security)
    • Handles embedded images in the rich text field (poorly: making a custom "Image" content type in Contentful might be the best workaround)
    • Is extensible using the transform_options prop
    • TODO: Handle linking to other pages in the site using Contentful's Embedded Entries and Gatsby's Link component

Example without extending the transform options:

import React from 'react'
import ContentfulRichText from 'gatsby-theme-contentful/src/components/ContentfulRichText'
import { StaticQuery, graphql } from 'gatsby'
import { BLOCKS } from '@contentful/rich-text-types'

export default () => <StaticQuery query={graphql`
    query {
      contentfulSample {
        someRichTextField {
          json
        }
      }
    }
  `}
    render={data => {
      return(
        <ContentfulRichText richTextJSON={data.contentfulSample.someRichTextField.json}/>
      )
    }}
/>

Example with some custom transform options

import React from 'react'
import ContentfulRichText from 'gatsby-theme-contentful/src/components/ContentfulRichText'
import { StaticQuery, graphql } from 'gatsby'
import { BLOCKS } from '@contentful/rich-text-types'
import CustomImage from '../components/CustomImage'

export default () => <StaticQuery query={graphql`
    query {
      contentfulSample {
        someRichTextField {
          json
        }
      }
    }
  `}
    render={data => {
      console.log(data)
      const transform_options = {
        renderNode: {
          [BLOCKS.EMBEDDED_ASSET]: (node) => {
            const { title, description, file } = node.data.target.fields;
            const mimeType = file['en-US'].contentType
            const mimeGroup = mimeType.split('/')[0]
      
            switch (mimeGroup) {
              case 'image':
                return <CustomImage
                  title={ title ? title['en-US'] : null}
                  alt={description ?  description['en-US'] : null}
                  src={file['en-US'].url}
                  className='custom-class'
                />
              default:
                return <span style={{backgroundColor: 'red', color: 'white'}}> {mimeType} embedded asset </span>
            }
          }
        }
      }
      return(
        <ContentfulRichText richTextJSON={data.contentfulSample.someRichTextField.json}/>
      )
    }}
/>