GatsbyConf - Decoupling Drupal Using Gatsby: A Crash Course workshop

Overview

GatsbyConf - Decoupling Drupal Using Gatsby: A Crash Course workshop

1 - Get the code on your local machine

Use git to clone the code repository

git clone https://github.com/octahedroid/gatsbyconf.git

cd gatsbyconf

Install dependencies

yarn 

Start Gatsby on develop mode

yarn develop

2.A - Rendering field data

Open page file:

src/pages/{nodePage.path__alias}.js

Remove JSON output

    { JSON.stringify(node, {}, 2) }

Import components

import Title from "../components/field/title";
import Body from "../components/field/body";

Add components to the page

{node.title}


2.B - Show/Hide field title feature

Open page file:

 src/pages/{nodePage.path__alias}.js

Add field_show_title to GraphLQ Query

    field_show_title

Replace original code:

{node.title}

With this code containing the field_show_title value validation to show/hide title

{ node.field_show_title && {node.title} }

3.A - Serve images from Drupal CMS

Open page file:

 src/pages/{nodePage.path__alias}.js

Add bodyProcessedWithInlineImages field to GraphLQ Query

# GraphQL Customization Fields
fields {
  bodyProcessedWithInlineImages
}

Update Body component to use previously added field



Check gatsby-node.js for code to replace image relativePath with remotePath

3.B - Serve images as Gatsby Images

Open page file:

src/pages/{nodePage.path__alias}.js

Add inlineImages field to GraphLQ Query

# GraphQL Customization Fields
fields {
    inlineImages {
      originalImageUrl
      localFile {
        childImageSharp {
          gatsbyImageData(width: 1024)
        }
      }
    }
}

Replace original Body compoenent with BodyInlineImages:

import BodyInlineImages from "../components/field/body-inline-images";

With the recently imported BodyParser component


   

Check gatsby-node.js for code to replace image relativePath with remotePath


4 - Replace Body field with Paragraphs and React components

Add relationships field

      relationships {
        field_components {
          __typename
          ...ParagraphBlogTeaser
          ...ParagraphHeroCta
          ...ParagraphImage
          ...ParagraphText
        }
      }

Check src/helpers/fragments.js for code to GraphQL query fragments

Import uuid library and componentResolver helper

import uuid from "react-uuid"
import { componentResolver } from "../helpers/component-resolver"

Call componentResolver helper

const components = componentResolver(node?.relationships?.field_components);

Check src/helpers/component-resolver.js file for resolvers

Replace BodyInlineImages component:


   

With the components array constant

{components &&
  components.map((item) => {
    return 
   
    {item}
   
})}

Remove no longer needed classNames at article html

">

  

It should look like this:


  

5.A - Rendering field data

Open page file:

src/pages/{nodeArticle.path__alias}.js

Remove JSON output

    { JSON.stringify(node, {}, 2) }

Import component

import Cover from "../components/cover";

Add fields to GraphQL Query

      created
      relationships {
        field_author: uid {
          field_full_name
          relationships {
            field_picture {
              relationships {
                field_media_image {
                  localFile {
                    childImageSharp {
                      gatsbyImageData(layout: FIXED, width: 48, height: 48)
                    }
                  }
                }
              }
            }
          }
        }
        field_image {
          relationships {
            field_media_image {
              localFile {
                childImageSharp {
                  gatsbyImageData(width: 1500)
                }
              }
            }
          }
        }
      }

Add code

const author = {
  name: node.relationships.field_author.field_full_name,
  picture: node.relationships.field_author.relationships.field_picture.relationships.field_media_image.localFile.childImageSharp,
}

Add Cover component to the page

">

  

5.B - Add CodeBlock Component

Open fragments file:

src/helpers/fragments.js

Add GraphQL query fragment to src/helpers/fragments.js file

export const ParagraphCodeBlock = graphql`
  fragment ParagraphCodeBlock on paragraph__code_block {
    field_title
    field_code
    field_language
    field_show_line_numbers
  }
`

Open page file:

src/pages/{nodeArticle.path__alias}.js

Add field_components and use fragments to relationships field

        field_components {
          __typename
          ...ParagraphText
          ...ParagraphCodeBlock
        }

Import uuid library and componentResolver helper

import uuid from "react-uuid"
import { componentResolver } from "../helpers/component-resolver"

Call componentResolver helper

const components = componentResolver(node?.relationships?.field_components);

Render the components array constant

{components &&
  components.map((item) => {
    return 
   
    {item}
   
})}

Remove no longer needed classNames at article html

">

  

It should look like this:


  

Open component resolver file:

src/helpers/component-resolver.js

Import CodeBlock component

import ParagraphCodeBlock from "../components/paragraph/paragraph-code-block";

Add code to resolve component

    if (component.__typename.includes(`paragraph__code_block`)) {
        return (
            
   
        )
    }

6 - Using Deferred Static Generation (DSG)

Open page file:

src/pages/{nodeArticle.path__alias}.js

Add a new config function to the page template

{ const pathAlias = `/${params.path__alias}`; return { defer: data.dsgArticles.nodes.some( article => article.path.alias === pathAlias ) } } }">
export async function config() {
  // GraphQL Query
  // - Fetch allNodeArticle filtered by field_rendering_mode equals to DSG
  // - Any other(s) filter(s) you could implement:
  //   - Articles created more than a year ago
  //   - Articles with low traffic (integarte with your analytics data)
  const { data } = graphql`  
  {
    dsgArticles: allNodeArticle (filter:{field_rendering_mode:{eq:"DSG"}}) {
      nodes {
        path {
          alias
        }
      }
    }
  }
  `

  return ({ params }) => {
    const pathAlias = `/${params.path__alias}`;
    return {
      defer: data.dsgArticles.nodes.some( article => article.path.alias === pathAlias )
    }
  }
}

Q & A

Other Drupal Modules:

You might also like...

A minimal e-commerce store using Gatsby, SANITY, Stripe, Use-Shopping-Cart and Netlify

🏪 Gatsby Starter Stripemart Like a supermarket but for Stripe. No ongoing monthly costs. Perfect for artists, creators and independent builders doing

Nov 14, 2022

A build plugin to integrate Gatsby seamlessly with Netlify

A build plugin to integrate Gatsby seamlessly with Netlify

Essential Gatsby Plugin This build plugin is a utility for supporting Gatsby on Netlify. To support build caching and Gatsby functions on Netlify, you

Dec 27, 2022

React Gatsby static web tool for generative artists working on token based NFT artwork (ex: Artblocks)

React Gatsby static web tool for generative artists working on token based NFT artwork (ex: Artblocks)

token-art-tools React Gatsby static web tool for generative artists working on token/hash based NFT artwork (ex: Artblocks) https://ctrlshiftmake.gith

Dec 15, 2022

GatsbyContactFormBasedOnFormikAnalysis - This is example contact form for gatsby framework.

Gatsby minimal starter 🚀 Quick start Create a Gatsby site. Use the Gatsby CLI to create a new site, specifying the minimal starter. # create a new Ga

Jan 2, 2022

Gatsby-Formik-contact-form-with-backend-panel - Full working contact form with backend GUI panel.

Gatsby minimal starter 🚀 Quick start Create a Gatsby site. Use the Gatsby CLI to create a new site, specifying the minimal starter. # create a new Ga

Jan 2, 2022

Gatsby-starter-minimal-blog - Typography driven, feature-rich blogging theme with minimal aesthetics.

Gatsby-starter-minimal-blog - Typography driven, feature-rich blogging theme with minimal aesthetics. Includes tags/categories support and extensive features for code blocks such as live preview, line numbers, and line highlighting.

Jan 29, 2022

A Gatsby-based starter theme with e-commerce styled components

A Gatsby-based starter theme with e-commerce styled components

This beautiful theme from the Matter Design Team gives you the styling and scaffolding for your next e-commerce site. You can customize to your heart'

Jan 3, 2023

A Gatsby storefront for a Shopify store.

Leah Gardner Storefront A Gatsby storefront for a Shopify store. Built as a learning project for Shopify and Gatsby integration. This project is boots

Dec 14, 2022

For this workshop, we're going to learn more about cloud computing by exploring how to use Pulumi to build, configure, and deploy a real-life, modern application using Docker

For this workshop, we're going to learn more about cloud computing by exploring how to use Pulumi to build, configure, and deploy a real-life, modern application using Docker. We will create a frontend, a backend, and a database to deploy the Pulumipus Boba Tea Shop. Along the way, we'll learn more about how Pulumi works.

Dec 29, 2022
Comments
  • Missing CodeBlock component

    Missing CodeBlock component

    Thanks so much for the gatsbyconf demo and walkthrough last week Jesus.

    In working through the README.md, I ran into a glitch with section 5.B. It seems that it's referencing a file that doesn't exist:

    import ParagraphCodeBlock from "../components/paragraph/paragraph-code-block";

    Any chance you could check that file in so we can see how that component works?

    opened by thegurf 2
Owner
Octahedroid
Octahedroid
A crash course on Zod - a schema validation library for TypeScript

Zod Crash Course This Zod crash course will give you everything you ever needed to know about Zod - an amazing library for building type-safe AND runt

Total TypeScript 339 Dec 28, 2022
Gatsby-blog-cosmicjs - 🚀⚡️ Blazing fast blog built with Gatsby and the Cosmic Headless CMS 🔥

Gatsby + Cosmic This repo contains an example blog website that is built with Gatsby, and Cosmic. See live demo hosted on Netlify Uses the Cosmic Gats

Priya Chakraborty 0 Jan 29, 2022
Starter-gatsby-blog - Gatsby starter for a Contentful project from the community.

Contentful Gatsby Starter Blog Create a Gatsby blog powered by Contentful. Static sites are scalable, secure and have very little required maintenance

Priya Chakraborty 0 Jan 29, 2022
Extract CSS custom properties and a JavaScript config from Drupal's theme breakpoints

Drupal breakpoints to CSS To eliminate the need for different places for breakpoints and only maintain a single source of truth for those, this node_m

Factorial 4 Nov 21, 2022
Bloxflip crash automation using the martingale strategy. Earn robux passively while you sit back!

bloxflip-autocrash Bloxflip crash automation using the martingale strategy. Earn robux passively while you sit back! ⚠️ WARNING This automation softwa

null 17 Dec 30, 2022
Three JS Crash kursi 2022 (Amaliyot asosida)

Video kurs: https://www.youtube.com/watch?v=NL2Cv8N1Skg Kursdagi presentatsiya: https://bit.ly/3aRRf9M Loyiha demosi: https://harmonious-puppy-4ea920.

Javohir Hakimov 5 Oct 28, 2022
Full-stack-todo-rust-course - we are building this out now in prep for the real course

full-stack-todo-rust-course wip - we are building this out now in prep for the real course Plan Come up with the requirements Create user stories Desi

Brooks Builds 89 Jan 2, 2023
We are students of group named "Special-Team" of GоIT academy. We graduated JavaScript course and for consolidate in practice 📌 knowledges received on this course, we together 🤝 developed graduation project

Проект сайту "Filmoteka" Привіт! ?? Ми студенти групи під назвою "Special-Team" академії GоIT ?? ?? Ми закінчили курс JavaScript і для того, щоб закрі

Oksana Banshchykova 12 Jan 3, 2023
Course material for a ~10 hours introductionary course for Julia. Topics: Introduction, Parallel Programming, Data Science

Development We use Franklin.jl to generate the lecture material. To do so, simply activate the environment, use Franklin and run the local server: act

GregorE 3 Dec 15, 2022
A new Node.js resource built using Gatsby.js with React.js, TypeScript, and Remark.

Nodejs.dev Nodejs.dev site built using Gatsby.js with React.js, TypeScript, SCSS, and Remark. You can find the latest Figma design protype here. ?? Ge

Node.js 2.2k Jan 5, 2023