Practice with GatsbyJS | InfoWorld

0

Somewhere between using a WYSIWYG editor like Wix and building your own stack from scratch with something like Webpack, you’re using a framework like Gatsby.

Gatsby is best known as a static site builder, although it also competes with full-fledged server-side rendering frameworks like Next.js and SvelteKit. Gatsby strives to make the development experience friendly and easy, while providing essential website features like modern out-of-the-box blurry images.

But unlike Next.js or SvelteKit, Gatsby is purely a front-end framework, not a full-stack. Therefore, Node.js is required for development, but not for deployment. For this, Gatsby supports several one-click deployment platforms, including Netlify and Gatsby Cloud.

Let’s dive into the nitty-gritty – this is the best way to get an idea of ​​how Gatsby works and what it offers. You will need access to a command line for a Node.js/NPM installation, as well as access to Git, which is used to download the starter kit. Once you have access to NPM from the command line, use it to install Gatsby globally by typing npm install -g gatsby-cli.

When that’s done, you should be able to type gatsby -v and get a response with the installed version. Start creating a new app with gatsby new. Gatsby will largely hold your hand throughout the interactive process, and any choices you make are subject to change later. I named my project “My Demo” and accepted the default location of my-demo.

When prompted to choose which CMS to use, you can accept “No (or I’ll add it later)” as the answer. The same goes for CSS processors. You can leave the choices blank for additional plugins to add.

Run the Gatsby starter app

You can now run the application in development mode by cd-ing to the new directory (my-demo) and typing gatsby develop.

Once this is running, you can visit localhost:8000 and see the welcome screen like in Figure 1.

Figure 1. Gatsby welcome screen

new gatsbyjs website IDG

Hot swapping the module

Gatsby comes with HMR (hot module replacement) active, so go ahead and modify the </code> item in /src/pages/index.js to be <code><title>My Home Page> and you will immediately see this change reflected in the browser. (Make sure the app is running in development mode; either the process is running in the background or you’re opening a new command line window.)

Add Page

Gatsby is built on React, so you have the full range of React capabilities at your disposal. A key fact about development in Gatsby is that every page is a React component. Even the index page is a React component. You can verify this by opening this file and observing that it defines a function (const IndexPage = () => { return (...)) and then exports it as a JS module (export default IndexPage). In short, the index.html file exports a React functional component that represents the index page.

Let’s add a new page and simplify things. Create a new /src/pages/mypage.js file and give it the contents of Listing 1.

Listing 1. Add a simple page

import * as React from "react";
const MyPage = () => {  return (
        My New Page
)}
export default MyPage;

Added navigation

You can visit the new page at localhost:8000/mypage. Now add a link from your new page to the index page. Add Gatsby’s built-in Link component by importing it:

import { Link } from 'gatsby'

Now add it to your page with Home. The link will appear and you can click on it to go to the index page.

Creating a shared component

Now add a new src/components/Dog.js file. (Note that you also add the components directory.) Place the contents of Listing 2 in this file.

Listing 2. The Dog component

cat src/components/Dog.js
import * as React from "react";
const DogComponent = ({ name }) => {
        return (
{name} says Woof!
        )}     
export default DogComponent;

This is a typical React reusable component that accepts a single prop (name), which is then used in markup via token syntax. You can use it in page components as shown in Listing 3.

Listing 3. Using the Dog component

import Dog from '../components/Dog.js';
//...

There’s nothing Gatsby-specific here, except that your shared components do not go to the pages directory. (Note that there is nothing special about the component directory name.)

Use pictures

One of Gatsby’s claims to fame is its sophisticated image support. This is now delivered via official plugins. Let’s add images to the Dog component. Start by installing the NPM packages as shown in Listing 4.

Listing 4. Installing Image Plugins and Dependencies

npm install gatsby-plugin-image gatsby-plugin-sharp gatsby-source-filesystem gatsby-transformer-sharp

Listing 4 installs four different plugins used by Gatsby to manage images and load them from the filesystem. Now register the plugins with Gatsby by editing the gatsby-config.js file in the project root directory. This file has an empty plug-ins entry in the module export. Add the plug-in entries seen in Listing 5.

Listing 5. Registering image plugins in gatsby-config.js

plugins: [ `gatsby-plugin-image`, `gatsby-plugin-sharp` ]

The two image plugins include one for dynamic images (images driven by data, i.e. which can change depending on the state of the application) and one for static images, which always remain the same. In this case, we’ll just use a static image.

Open the /src/components/dog.js file and add the import and component as shown in Listing 6.

Listing 6. Using the StaticImage component

import * as React from "react";
import { StaticImage } from "gatsby-plugin-image";

const DogComponent = ({ name }) => {
        return (
          


                Foo2
               

               
               

                {name} says Woof!
          

        )}     
export default DogComponent;

Listing 6 imports the StaticImage component from the gatsby-plugin-image package and uses it to display the image at the given URL. Note that if you want to load files from the local filesystem, you will also need to import gatsby-source-filesystem and configure it to point to the location(s) where your image files reside (see here). If you want to use dynamic images, you use the GatsbyImage component and you need to include the gatsby-transformer-sharp plugin.

Gatsby and GraphQL

Another notable feature of Gatsby is its extensive use of GraphQL, which is a query language created by Facebook. GraphQL can pull data from many sources for use by your components. This feature is used in many Gatsby plugins to unify the way data is loaded.

I’ll give you an idea of ​​how it works by extracting data from the information defined in the gatsby-config.js file. A similar process is used to access files from the file system and data from content management systems and databases.

First, look at gatsby-config.js. Note that it exports a few metadata fields, as shown in Listing 7.

Listing 7. gatsby-config.js exports

module.exports = {
  siteMetadata: {
    siteUrl: "https://www.yourdomain.tld",
    title: "My Demo",
  }

Now open the src/pages/mypage.js file and access this metadata as shown in Listing 8.

Listing 8. Accessing metadata with GraphQL

import * as React from "react";
import { Link, useStaticQuery, graphql } from 'gatsby';
import Dog from '../components/Dog.js';

const MyPage = () => { 
const data = useStaticQuery(graphql`
    query {
      site {
        siteMetadata {
          title
        }
      }
    }
  `)
return (
       

{data.site.siteMetadata.title}
          Home
       


       

)}

export default MyPage;

Modifications to Listing 8 begin with importing the useStaticQuery and graphql packages of gatsby. In the body of the markup, you can see a token accessing site metadata with {data.site.siteMetadata.title}. But where does this data come from?

Before return statement, the data variable is populated with a call to useStaticQuery, and this defines a GraphQL query that accesses the site’s metadata. These queries have access to page variables such as query parameters, and therefore can be fully dynamic when accessing the data store (i.e. using entity ids).

GraphQL is probably the biggest barrier to Gatsby adoption, due to its seemingly complex interface. But in the long run, GraphQL provides a powerful approach to unified data querying.

Gatsby the magnificent

You’ve tasted some of Gatsby’s abilities. Gatsby sports an extensive plugin ecosystem, with both official and community-created plugins. It’s a good starting point whenever you need something.

Gatsby continues to evolve to keep pace with industry changes. This is a tempting option, especially when looking to create static sites like blogs.

Learn more about JavaScript development

Copyright © 2022 IDG Communications, Inc.

Share.

About Author

Comments are closed.