Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Free Learning
Arrow right icon
Elevating React Web Development with Gatsby
Elevating React Web Development with Gatsby

Elevating React Web Development with Gatsby: Practical guide to building performant, accessible, and interactive web apps with React and Gatsby.js 4

eBook
$24.99 $35.99
Paperback
$43.99
Subscription
Free Trial
Renews at $19.99p/m

What do you get with Print?

Product feature icon Instant access to your digital eBook copy whilst your Print order is Shipped
Product feature icon Paperback book shipped to your preferred address
Product feature icon Download this book in EPUB and PDF formats
Product feature icon Access this title in our online reader with advanced features
Product feature icon DRM FREE - Read whenever, wherever and however you want
Product feature icon AI Assistant (beta) to help accelerate your learning
OR
Modal Close icon
Payment Processing...
tick Completed

Shipping Address

Billing Address

Shipping Methods
Table of content icon View table of contents Preview book icon Preview Book

Elevating React Web Development with Gatsby

Chapter 1: An Overview of Gatsby.js for the Uninitiated

In this book, we will take your existing React knowledge and supplement it with Gatsby.js (which we will refer to as Gatsby from now on) to create performant and accessible static sites. I hope to give you the tools you need to create better websites using Gatsby and get you to join the static site revolution. So, happy hacking!

This chapter starts with a brief historical look at the static web and why Gatsby was created. Then, we'll think about what Gatsby is and how it builds on React. Next, we'll go through some of the use cases of Gatsby and identify Gatsby's competitors. Finally, we'll set up a basic Gatsby project, having created our first few pages.

In this chapter, we will cover the following topics:

  • A brief history of the static web
  • What is Gatsby?
  • Gatsby use cases
  • Gatsby's competitors
  • Setting up a project

Technical requirements

A brief history of the static web

Static sites have been around nearly as long as the internet itself. They are the original blueprint for any website – HyperText Markup Language (HTML), Cascading Style Sheets (CSS), and JavaScript (JS). In the 1990s, HTML was the only publishing mechanism for the web. To get content on the internet, you would have to create a static HTML file and expose it to the internet via a server. If you wanted to modify one of your web pages, you would need to change its corresponding HTML file directly.

While learning HTML is part of primary education these days, back in the 1990s, it was a novel skill to understand and write the language. Creating or editing content was costly, as you would require someone with this skill set for every modification. Luckily, Content Management Systems (CMSes) (WordPress, Drupal, and so on) soon swooped in to allow non-technical users to control a webpage's design and content. It also gave users the ability to store and manage files via a user interface. CMSs continue to be utilized today with increasing popularity. The number of websites using a CMS has risen from 23.6% to 63% in the last decade. Over 75 million sites use WordPress today – that's 30% of the web!

At an almost identical pace, frontend frameworks and libraries have gained notoriety. Building single-page applications became commonplace. Today, the most dominant UI library in the JS world is Facebook's React.js, which is a small library with a handful of functions but some big ideas – a virtual DOM, JavaScript Syntax Extension (JSX), and componentization. There is no denying how much impact React has had on web development. In 2020, 80% of JS developers had used it, and 70% of JS developers said they would use it again.

Frontend frameworks have entirely changed how developers approach web development, giving them the flexibility to focus on functionality over content and drastically speeding up their workflows. But you're only as fast as your slowest team member. The clunky nature of CMS platforms was revealed when developers started to employ these frameworks and integrate them with CMSs. Traditional CMS workflows made use of databases and environments that frontend frameworks had removed from the equation. Combining this with CMS security and bottleneck issues led to the rebirth of static sites.

Kyle Mathews, the founder of Gatsby, was a catalyst for this trend. He noticed that the expectations on website accessibility and performance increased dramatically. He observed apps investing millions of dollars in user experience. There is no denying that the disparity between a 2005 and 2015 website was significant. In a competitive environment such as the web, you have to have a product that can stand out. Mathews took a step back, identified gaps in existing tooling, and asked what the ideal product might be. This research is what led him to create Gatsby.

It's almost poetic that we have gone full circle and returned to static content because there is no beating it when it comes to speed and performance.

What is Gatsby?

Gatsby is a free, open source static site generator that harnesses React. Static site generators are software applications that create static pages from a template or component and supplement them with content from a source. Static site generators are an alternative to a more traditional database-driven CMS, such as WordPress. In these conventional systems, content is managed and stored in a database. When the server receives a particular URL request, the server retrieves data from the database, mixes it with a template file, and generates an HTML page as its response. Generating HTML on demand can be a time-consuming process and can leave the user twiddling their thumbs or, worse, leaving your site. Bounce rates (the percentage of visitors to a particular website who navigate away from the site after viewing only one page) hover below 10% for websites that take less than 3 seconds to load, but the number jumps to 24% for a 4-second load time and 38% for a 5-second load time.

Static site generators like Gatsby, on the other hand, generate pages during a build process. During this process, Gatsby brings in data to its GraphQL layer, where it can be queried in pages and templates. The requested data is then stored in JSON and accessed by the built pages, which are composed of HTML, JS, and CSS files. A user can deploy these generated pages to a server. When it receives a request, the server responds with predetermined, static, rendered HTML. As these static pages are generated at build time, they eliminate the latency that databases would introduce. You can even do away with web servers altogether and have your site served via a CDN pointing to a storage medium, such as an AWS Simple Storage Service (S3) bucket. The difference is striking; web experiences built with Gatsby are lightning fast, as nothing can be faster than sending static content.

Important Note

A static site can contain dynamic and exciting experiences! It is a common misconception that "static" means the site is stationary. This could not be further from the truth. The word "static" only refers to the manner in which files are retrieved by a client.

While Gatsby is known for static site generation, recent versions also include server-side and deferred static generation, rendering functionality for when static generation is not enough.

Aside from creating a blazing-fast user experience, Gatsby also has a focus on developer experience. As we learn and build, I'm sure you will start to recognize how easy it is to use. The way it achieves this can be broken down into four steps.

Community

Gatsby has an incredibly supportive community backing. At the time of writing, over 3,600 people have contributed to the Gatsby repository. This is further amplified by the plugin ecosystem surrounding Gatsby; the community has created more than 2,000+ plugins that abstract complex functionality that other developers may wish to use in their own projects. These plugins are distributed as packages stored on a JS repository, such as NPM, that can be added to your project in a few lines. They can extend your site by sourcing content, transforming data, creating pages, or theming your application.

Sourcing content from anywhere

Every day, the amount of data we need to combine to create experiences is rising. In traditional React applications, managing multiple sources of data could become a nightmare. Storing, massaging, merging, and querying data all require complex solutions that struggle to scale.

Gatsby does this differently. Whether you are sourcing data from a CMS, real-time database, or even a custom Application Programming Interface (API), you can merge all of this data into a unified data layer. The Gatsby community is constantly contributing source plugins to allow you to ingest data from your favorite sources with ease. Nine times out of ten, you won't need to write a single line of code to source your data, but for the times when you do, we will be covering plugin creation in Chapter 10, Creating Gatsby Plugins.

Once ingested into this data layer, we can explore and query all our sources of data in one place using a uniform data layer. Using the power of GraphQL, we can query our data in the same way when rendering pages regardless of their source. The GraphQL layer is transitory and doesn't exist after the application has been built, so doesn't affect the size of your production site. If GraphQL is something new to you, don't worry – I will be explaining how it works in Chapter 3, Sourcing and Querying Data (from Anywhere!).

Building tooling you already know

Often when we approach new technologies, we are faced with a steep learning curve as we understand new syntax and ways of thinking. In Gatsby, we build on your existing knowledge of React instead of starting from scratch. Underpinning all of our code is the same React component model many of you already know. You should feel pretty confident from the beginning, as the code should look familiar, and if you're not, Gatsby can also help you learn React from a more "content-driven" approach.

Supercharging web performance

As web developers, we can spend considerable time tinkering with websites to squeeze every ounce out of their performance. Sometimes, this can take as long, if not longer, than building the design. Also, performance gains can sometimes be undone instantly by a change to the site design outside of your control. It's because of this that some large organizations have dedicated teams to improve site performance. But it doesn't have to be this way! As we start to build together, you will see that load times go from seconds to milliseconds, and your site will feel far more responsive than a conventional React app. Gatsby has plenty of tricks up its sleeve that improve performance, some of which we will touch on at the end of this chapter. It also turns your site into a Progressive Web App (PWA) with just a few lines of code – if that's not cool, I don't know what is!

Important Note

An essential distinction between Gatsby and React is that Gatsby is a "framework," not a "library." When using a library, you control your application flow; you call it when you need it. When using a framework, however, there is an inversion of control. Frameworks command that you adhere to a particular flow and layout defined by them. Working within a framework can often be seen as a benefit, as any developer familiar with the framework will know where to find relevant files and code.

I hope you are beginning to see some of the great reasons why Gatsby is such a powerful tool. Let's now see it in action.

Gatsby use cases

You might be starting to realize that Gatsby could have applications across many different kinds of websites. Since Gatsby's v1 launch in 2017, the framework has been used in a multitude of different ways by companies both big and small. Here, I want to highlight some examples of use cases where Gatsby excels and suggest why companies may have chosen Gatsby for these sites.

Tip

While reading about these example sites here is great, I highly encourage you to visit them via your own device. One of Gatsby's best features is the speed of the sites it creates, and it is essential to experience this for yourself to understand the benefit.

Documentation sites

Documentation sites are a perfect use case for Gatsby as their content is primarily, if not entirely, static. Their content does not shift often either, with pages needing infrequent updates. Their static nature means that we can generate all page routes during the build process and load them onto a CDN, meaning that when a page is requested, the request is near-instant. It is for this reason that you see sites such as the official React documentation (https://reactjs.org) being made with Gatsby:

Figure 1.1 – The React documentation website

Figure 1.1 – The React documentation website

Due to the infrequent nature of updates to documentation pages, you can automate the build and deployment of your site as and when changes to documentation are made. With GitHub integrations or webhooks, you can get your documentation site to redeploy each change to a master branch or on a daily basis, for example. We will be exploring how to create these kinds of processes in Chapter 9, Deployment and Hosting.

Online courses

Online courses often have a unique structure – the majority of their content is in static learning modules, but they also require a small quantity of authenticated routes for logged-in user experiences.

Websites such as DesignCode.io (https://designcode.io/courses) utilize Gatsby for their static content, meaning their static pages are incredibly performant, and they then render authenticated routes on the client. While this does increase bundle size, as they need to ship more JS, the benefit of the fast static pages far outweighs the cost of heavier authenticated pages:

Figure 1.2 – The DesignCode.io website

Figure 1.2 – The DesignCode.io website

One of the most popular sources of data for Gatsby is MDX. MDX is a powerful format that allows you to write JSX within Markdown. Why is it awesome? Because you can include React components alongside documentation with no hassle at all. React components can be far more interactive and dynamic than text, and as a result, it is a powerful format to create online courses on, as you can create content that is more enticing for the user. Perhaps a more interactive course is a more memorable one? We will be diving into MDX in detail in Chapter 3, Sourcing and Querying Data (from Anywhere!).

SaaS products

When selling Software as a Service (SaaS) online, your website's performance can be considered a reflection of your product's performance. As a result, having a clunky website can be the difference between your product being a success or not. As mentioned previously, this is an example where you could go down a rabbit hole to improve your site's performance. Companies such as Skupos (https://www.skupos.com/) use Gatsby to get more performance benefits for free. Gatsby also works wonders for Search Engine Optimization (SEO). As pages are prerendered, all your page content is available to web crawlers such as Googlebot to navigate to your site. The speed and SEO improvements help their product's website stand out and give the user confidence that they know what they are doing when it comes to technology:

Figure 1.3 – The Skupos website

Figure 1.3 – The Skupos website

Skupos also supplement their site pages with metadata and alt-text, which further aids web crawlers in understanding site content. The more web crawlers understand your site's content, the better your search engine ranking will be.

Design agencies and photo-heavy sites

In cases where your work is more visual, your site often needs to make use of large quantities of high-resolution images. We've all visited a website and felt like we were transported back to the dial-up days as we've waited for large image files to load. This common mistake is often amplified further by a large amount of cumulative layout shift that happens when loading images. Gracefully handling the image's loading state to avoid this can be a headache.

Gatsby performs magic for images within its application. It utilizes the sharp library (https://github.com/lovell/sharp) under the hood to convert your large images into smaller web-friendly sizes. When your website loads, it will first load in a smaller resolution version before blurring up to the maximum resolution required. This results in no layout shift and a far less "jumpy" experience for your site visitor. A great example of this is on the Call Bruno Creative Agency (https://www.callbruno.com/en/reelevant) website developed with Gatsby:

Figure 1.4 – The Call Bruno Creative Agency website

Figure 1.4 – The Call Bruno Creative Agency website

They use lots of imagery across their project pages, but the image load does not take you out of the experience. We will get into detail on handling images in Chapter 5, Working with Images.

By exploring these sites, we can see examples across industries where Gatsby is helping companies get ahead of their competition.

Gatsby's competitors

While this book focuses on Gatsby, it is crucial to understand that it is not the only React static site generator on the market. The competitor most often uttered in the same breath is Next.js.

Until recently, the key difference between Next.js and Gatsby was server-side rendering. Like Gatsby, a Next.js application can be hosted statically, but it also used to be able to server render pages where Gatsby could not. Instead of deploying a static build, a server is deployed to handle requests. When a page is requested, the server builds that page and caches it before sending it to the user. This means that subsequent requests to the resource are faster than the first call. As of version 4, Gatsby can have all of its pages prebuilt statically or it can create a hybrid build – a mixture of static and server-side rendered content. We will discuss this more in Chapter 9, Deployment and Hosting.

One major drawback to Next.js is its data security. When building Gatsby sites as static builds, data is only taken from the source at build time, and as the content is static, it is secure. Next.js keeps data stored on the server and, as such, it is easier to exploit. Next.js commonly requires more initialization if you wish to set it up via a server or using databases. This also means that there is more maintenance required in Next.js applications. Both Next.js and Gatsby have additional utilities to help with the handling of images. Gatsby, however, can make images more performant on statically rendered pages, while Next cannot.

The good news is that all static site generators follow a similar process. The skills and mentality you learn in this book are easily transferable to a different generator in the future should you decide you want to make the switch.

Now that we understand where Gatsby excels, let's start creating our first Gatsby project.

Setting up a project

In order to help you put into practice what you're learning, we will be building a project together. Throughout this book, we will be working to build a personal portfolio, something that every developer needs and therefore something I think will be relevant for most readers. The portfolio will contain blog pages to aid your learning in public, project pages to demonstrate your work, a stats page showcasing interesting metrics on your site, as well as many more features that will help your portfolio stand out from the crowd.

Throughout this book, you will be faced with options. We will discuss different implementations for styling your site, as well as data sources you may want to implement. This should give you the flexibility to align it with your current knowledge. Alternatively, you can throw yourself in the deep end – the choice is up to you. Everywhere there is a choice, I will also provide my personal recommendation for what might be best if you can't decide.

To see a finished version of the portfolio we will be building, visit this link:

https://elevating-react-with-gatsby.sld.codes/

Tip

Refer to the code repository (https://github.com/PacktPublishing/Elevating-React-Web-Development-with-Gatsby-4) that accompanies this book if you're struggling at any point. It includes a copy of the project as it should appear after every chapter.

To start using Gatsby, we need to ensure we have a few prerequisite tools set up on our machines. Most of these prerequisites are most likely already on your device if you are a React developer, although I would still encourage you to read through this list, as some of your tools may need an update.

Node.js version 14.15.0+

As of version 4.0, Gatsby supports all Node.js versions greater than 14.15.0. You can quickly check if you have Node.js installed by opening up a terminal window and typing the following:

 node -v

If you have Node.js installed, this should print a version number. However, if you receive an error, you can download Node.js by navigating to the Node.js website (https://nodejs.org). Node.js comes bundled with npm, a package repository, package manager, and command-line tool that we will be using to install Gatsby.

Tip

You're most likely already using Node.js, and some of your pre-existing projects may require a different version than the requirements specified here. If you need to manage multiple versions of Node.js on the same device, you should check out the Node.js Version Manager (NVM)(https://github.com/nvm-sh/nvm). It gives you access to valuable commands, including installing new versions and switching between minor and major versions of Node.js.

Gatsby command-line interface

The Gatsby Command-Line Interface (CLI) is a tool built by the core Gatsby team; it allows you to perform standard functions, such as creating new Gatsby projects, setting up local development servers, and building your production site. Although you can use it on a per-project basis, it is far more common to install the CLI globally so that you can use its features across multiple Gatsby projects without having to install it as a package in each project – got to save that hard-drive space!

To install the CLI globally, npm install it with the global flag:

npm i -g gatsby-cli

To verify its installation, open up a terminal window and type the following:

gatsby --help

If running this provides a list of commands and does not error out, then you're good to go.

Important Note

Throughout this book, I use npm as my package manager. If you prefer Yarn, you can use the Yarn equivalent commands.

Directory and package setup

Here, we will begin to create the files and folders we need to start our project, as well as install necessary dependencies such as React and Gatsby.

First, create a folder to house our project. You can call it whatever you like. Throughout this book, I will refer to this folder as the root folder of the application. Open a terminal and navigate to your root folder. Initialize a new package in this folder by running the following:

npm init -y

With the package now initialized, let's install React and Gatsby:

npm i gatsby react react-dom

Open your root folder in your favorite Integrated Development Environment (IDE). You should notice that it now contains three new items, package.json, package-lock.json, and a node-modules folder. Opening your package.json, you should see the following:

{
  "name": "gatsby-site",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "dependencies": {
    "gatsby": "^4.4.0",
    "react": "^17.0.2",
    "react-dom": "^17.0.2"
  }
}

In the preceding example, you can see that this file now contains references to the dependencies we have just installed.

Development scripts

Let's start by modifying package.json so that it contains some useful scripts that will speed up our development process:

{
  "name": "gatsby-site",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "build": "gatsby build",
    "develop": "gatsby develop",
    "start": "npm run develop",
    "serve": "gatsby serve",
    "clean": "gatsby clean"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "dependencies": {
    "gatsby": "^4.4.0",
    "react": "^17.0.2",
    "react-dom": "^17.0.2"
  }
}

Let's break down these scripts:

  • build: Runs the Gatsby CLI's build command. This creates a compiled, production-ready build of our site. We will learn more about this in Chapter 9, Deployment and Hosting.
  • develop: Runs the Gatsby CLI's develop command. We will review it in detail in the next section, Creating your first few pages.
  • start: The start script redirects to the develop script. This is in place as it is common to start packages with a start script.
  • serve: Runs the Gatsby CLI's serve command to serve up a Gatsby build folder. This is a useful way to review a production build.
  • clean: The clean script utilizes the Gatsby CLI's clean command. This deletes the local Gatsby cache and any build data. It will be rebuilt with the next develop or build command.

All of these scripts can be run from the root folder with the following command:

npm run script-name

Simply replace script-name with the name of the script you would like to run.

You'll notice the absence of a test script. Don't worry – we will get into how to test a Gatsby application in Chapter 7, Testing and Auditing Your Site.

Framework files and folders

As mentioned, Gatsby is a framework. Frameworks require certain files to exist in order to work. Let's set up our project with the files and folders where Gatsby expects to find them.

Create a gatsby-config.js file in your root directory and add the following:

module.exports = {
  plugins: [],
};

As the name might suggest, the gatsby-config.js file is the core configuration file for Gatsby. We will be coming back to this file frequently as we build out our project. By the time we are done with it, it will be full of plugins, metadata, styling, and even offline support.

Create gatsby-browser.js and gatsby-node.js files in your root directory. Both of these files can be left blank for now. The gatsby-browser.js file contains any code we would like to run on the client's browser. In the next chapter, we will be using this file to add styles to our website. The gatsby-node.js file contains code we would like to run during the process of building our site.

Finally, create an src folder in your root directory. This folder will contain the majority of our development work, much like in a traditional React application. Pages we create and components we define will all be contained within this folder.

Before we go any further, let's make sure we have our version control tracking the right files.

Using version control

I suspect many of you would like to use version control while you build out your Gatsby site. To ensure Git tracks only the files that matter, create a .gitignore file and add the following:

node_modules/
.cache/
public

These lines stop our dependencies, Gatsby builds, and cache folders from being tracked.

Creating your first few pages

We now have all the underlying code we need set up to allow us to start creating pages. In this section, we will create a three-page website using Gatsby. It's important to note that this is a basic example purely designed to solidify your understanding of how Gatsby works before we worry about styling and additional functionality.

Navigate to your src directory and create a new folder called pages. Any JS files we create within the pages folder will be treated as a route by Gatsby. This also applies to subfolders within the pages folder. There is, however, one exception – files called index.js are treated as the root of their directory. Let's make sense of this with a few examples:

  • src/pages/index.js will map to yourwebsite.com.
  • src/pages/about.js will map to yourwebsite.com/about.
  • src/pages/blog/my-first-post.js will map to yourwebsite.com/docs/my-first-post. While we won't be setting up a page at this URL now, we will start using routes such as this one in Chapter 3, Sourcing and Querying Data (from Anywhere!).
  • src/pages/404.js will map to any page that does not resolve on .

    Important Note

    Any React components you place in the pages folder will become navigable routes on your site. As such, it is best to separate your components from your pages. A common pattern is to create a components folder that sits next to your pages folder in the src directory and import components you want to use in your pages.

The index page

Create an index.js file in your pages folder. As the index of the pages folder, this will become the landing of your website. We can now populate this file with the following code:

import React from "react"
const Index = () => {
    return (
        <div>
            <h1>My Landing Page</h1>
            <p>This is my landing page.</p>
        </div>
    )
}
export default Index

The contents of this file should look familiar; it's just a simple stateless ReactJS component.

We could have also defined it as:

import React from "react"
export default function Index(){
    return (
        <div>
            <h1>My Landing Page</h1>
            <p>This is my landing page.</p>
        </div>
    )
}

Both examples will output the exact same result, so it's just personal preference.

The about page

In a similar fashion, we can create an about page. Here, you have a choice – you can either create this page at src/pages/about.js or at src/pages/about/index.js. The question I always ask myself when deciding which option to go with is whether the page will have sub-pages. In the case of an about page, I think it's unlikely to contain any sub-pages, so I will opt for src/pages/about.js:

import React from "react"
export default function About(){
    return (
        <div>
            <h1>My About Page</h1>
            <p>This is a sentence about me.</p>
        </div>
    )
}

Here, we have defined another simple React component containing a heading and paragraph to create our about page.

The 404 page

Gatsby expects to find a 404.js file in your pages directory. This page is special. It contains the page that will be shown when Gatsby cannot find a page that was requested. I am sure you have come across "Page not found" pages before. Without this page, on requesting a non-existent route, the browser will not find any resource and show a browser error to the user. While the 404 page is another form of displaying the same error, by creating this page, we can manage the error ourselves. We can link to working pages on our site or even suggest the page they might have been trying to visit (more on this in Chapter 3, Sourcing and Querying Data (from Anywhere!)).

Let's create our 404 page now in src/pages/404.js:

import React from "react"
export default function NotFound(){
    return (
        <div>
            <h1>Oh no!</h1>
            <p>The page you were looking for does not
               exist.</p>
        </div>
    )
}

You should be starting to see a pattern. Creating pages is as simple as defining React components – something you should be familiar with already.

Trying the develop command

At this point, you've actually already created a fully working website. Congratulations! To test it out, open a terminal at your root directory and run the following:

npm run start

As you will recall from our package.json, this will run the gatsby develop command. This will take a few seconds to run, but you should then see some terminal output that looks like this:

You can now view gatsby-site in the browser.
  http://localhost:8000/

You can now open a browser of your choice and navigate to http://localhost:8000/, and you should be greeted with something like this:

Figure 1.5 – The landing page preview

Figure 1.5 – The landing page preview

This is the rendered version of our index.js page component. You can modify the URL in your browser to http://localhost:8000/about to see your about page and http://localhost:8000/404 to see your 404 page. You can also see your 404 page in development by navigating to any invalid route and pressing the Preview custom 404 page button.

Tip

If you don't want to manually navigate to the browser and type in the URL, you can modify our scripts by appending the gatsby develop command with the -o option. This instructs Gatsby to open your default browser and navigate to the site automatically when you run the develop command.

gatsby develop in detail

Running gatsby develop starts the Gatsby development server. This might be a little confusing, as we have previously mentioned how a Gatsby site is delivered as static content, but it's actually there to speed up your development process.

Imagine your site contains 10,000 pages; building the entirety of your site every time you make a small change to one page would take a long time. To get around this in development, Gatsby uses a Node.js server to build only what you need as and when it's requested. Due to it building on demand, it can negatively affect the performance of a page and you should never test performance on a page in development for this reason.

Once the server is up, you can continue to edit your code without rerunning the command. The development server supports hot reloading, a concept that should be familiar to you.

The develop command has a number of built-in options that allow you to customize it:

  • -H, --host: Allows you to modify the host
  • -p, --port: Allows you to modify the port Gatsby runs on
  • -o, --open: Opens your project in the browser
  • -S, --https: Turns on HTTPS

You can view your site on any device connected to the same network by using the host option. This can be useful when you want to compare how your site behaves on mobile browsers with that of a desktop experience. To achieve this, run the following command:

gatsby develop -H 0.0.0.0

If the command is successful, you will see a subtle difference in the output:

You can now view gatsby-site in the browser.
  Local:            http://localhost:8000/
  On Your Network:  http://192.168.1.14:8000/

The develop command has added a URL for testing on your network. Typing this into a browser on any device connected to the same network will render your site.

Connecting your pages

Now that you have multiple pages, you may want to navigate between them. There are two different ways of achieving this – with the Gatsby Link component or via programmatic navigation. To some of you, these components and functions may sound familiar; this is because Gatsby wraps the reach-router (https://reach.tech/router) library for navigation. For those who haven't used reach-router before, the library comes with support for server-side rendering and routing accessibility functionality built in. Gatsby has built on and enhanced this functionality to meet its high standards for user accessibility, ensuring a great website experience regardless of who you are.

The Gatsby Link component

It's important to use the Gatsby <Link/> component as a replacement for the <a/> tag whenever you are linking to a page that is internal. The <Link/> component works just like an <a/> tag, with one important distinction – it enables prefetching. Prefetching is the act of loading a resource before it is required. This means that when the resource is requested, the time waiting for that resource is decreased. By prefetching the links on your page, your next click navigates to content that is already loaded and is therefore practically instant. This is particularly noticeable on mobile devices in areas with reduced network conditions that would normally have a delay when loading pages.

The first place you could add a Link component is to your 404 page. It's common for these pages to have a button that says something like "Take me home" that, when clicked, navigates to the landing page:

import React from "react"
import {Link} from "gatsby"
export default function NotFound(){
    return (
        <div>
            <h1>Oh no!</h1>
            <p>The page you were looking for does not
               exist.</p>
            <Link to="/">Take me home</Link>
        </div>
    )
}

As you can see in the preceding code block, the Link component has a prop called to; this needs to be passed to the page that you want to navigate to relative to the root of your website. By passing the "/" prop, Gatsby will navigate to the root of your website.

You can also add a link to the about page from the index page:

import React from "react"
import {Link} from "gatsby"
export default function Index() => {
    return (
        <div>
            <h1>My Landing Page</h1>
            <p>This is my landing page.</p>
            <Link to="/about">About Me</Link>
        </div>
    )
}

You can see here that we instead pass "/about" to the to prop in the <Link/> component; this will navigate to our previously created about page.

Programmatic navigation

Occasionally, you may need to trigger navigation with something other than a click. Perhaps you need to navigate as a result of a fetch request, or when a user submits a form. You can achieve this behavior by making use of the Gatsby navigate function:

import React from "react"
import {navigate} from "gatsby"
export default function SomePage() => {
    const triggerNavigation = () => {
        navigate('/about')
    }
    return (
        <div>
            <p>Triggering page navigation via onClick.</p>
            <button onClick={()=> triggerNavigation()}>
                About Me
            </button>
        </div>
    )
}

Like the <Link/> component, the navigate function will only work for navigating to internal pages.

We now have a basic Gatsby site set up with the ability to navigate between pages.

Summary

I appreciate that most of the content in this chapter has been theoretical, but it's important to understand the "why" as well as the "how." In this chapter, we have cemented the baseline knowledge of what Gatsby is and grasped the guiding principles we will be using in further chapters to build our website. We've seen examples of where Gatsby is being used and the benefits it can bring. We discussed what dependencies you need and how to initialize Gatsby projects. We have also set up a complete basic Gatsby project and created the first few pages of our website. We then used the built-in Gatsby components and functions to link our pages together.

We will be referencing the theory we've outlined in this chapter throughout this book, but for now, let's turn our focus to styling our web application. In the next chapter, we will identify various different styling methodologies and make an informed choice about which one you should use for your project.

Left arrow icon Right arrow icon
Download code icon Download Code

Key benefits

  • Understand how to use Gatsby to build, test, and deploy an end-to-end website and manage SEO
  • Build reusable templates to streamline your workflows
  • Create plugins, add authentication, and work with real-time data

Description

Gatsby is a powerful React static site generator that enables you to create lightning-fast web experiences. With the latest version of Gatsby, you can combine your static content with server-side rendered and deferred static content to create a fully rounded application. Elevating React Web Development with Gatsby provides a comprehensive introduction for anyone new to GatsbyJS and will help you get up to speed in no time. Complete with hands-on tutorials and projects, this easy-to-follow guide starts by teaching you the core concepts of GatsbyJS. You'll then discover how to build performant, accessible, and scalable websites with the GatsbyJS framework. Once you've worked through the practical projects in the book, you'll be able to build anything from a personal website to large-scale applications with authentication and make your site rise through those SEO rankings. By the end of this Gatsby development book, you'll be well-versed in every aspect of the tool's performance and accessibility and have learned how to build client websites that your users will love.

Who is this book for?

This book is for web developers who want to use GatsbyJS with React to build better static and dynamic client-side apps. Prior experience of working with React basics is necessary. Knowledge of Node.js fundamentals will help you to get the most out of this web development book.

What you will learn

  • Understand what GatsbyJS is, where it excels, and how to use it
  • Structure and build a GatsbyJS site with confidence
  • Elevate your site with an industry-standard approach to styling
  • Configure your GatsbyJS projects with search engine optimization to improve their ranking
  • Get to grips with advanced GatsbyJS concepts to create powerful and dynamic sites
  • Supercharge your site with translations for a global audience
  • Discover how to use third-party services that provide interactivity to users
Estimated delivery fee Deliver to Ukraine

Economy delivery 10 - 13 business days

$6.95

Premium delivery 6 - 9 business days

$21.95
(Includes tracking information)

Product Details

Country selected
Publication date, Length, Edition, Language, ISBN-13
Publication date : Jan 21, 2022
Length: 314 pages
Edition : 1st
Language : English
ISBN-13 : 9781800209091
Languages :
Tools :

What do you get with Print?

Product feature icon Instant access to your digital eBook copy whilst your Print order is Shipped
Product feature icon Paperback book shipped to your preferred address
Product feature icon Download this book in EPUB and PDF formats
Product feature icon Access this title in our online reader with advanced features
Product feature icon DRM FREE - Read whenever, wherever and however you want
Product feature icon AI Assistant (beta) to help accelerate your learning
OR
Modal Close icon
Payment Processing...
tick Completed

Shipping Address

Billing Address

Shipping Methods
Estimated delivery fee Deliver to Ukraine

Economy delivery 10 - 13 business days

$6.95

Premium delivery 6 - 9 business days

$21.95
(Includes tracking information)

Product Details

Publication date : Jan 21, 2022
Length: 314 pages
Edition : 1st
Language : English
ISBN-13 : 9781800209091
Languages :
Tools :

Packt Subscriptions

See our plans and pricing
Modal Close icon
$19.99 billed monthly
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Simple pricing, no contract
$199.99 billed annually
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just $5 each
Feature tick icon Exclusive print discounts
$279.99 billed in 18 months
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just $5 each
Feature tick icon Exclusive print discounts

Frequently bought together


Stars icon
Total $ 136.97
Elevating React Web Development with Gatsby
$43.99
Full-Stack Web Development with GraphQL and React
$48.99
Designing React Hooks the Right Way
$43.99
Total $ 136.97 Stars icon
Banner background image

Table of Contents

17 Chapters
Part 1: Getting Started Chevron down icon Chevron up icon
Chapter 1: An Overview of Gatsby.js for the Uninitiated Chevron down icon Chevron up icon
Chapter 2: Styling Choices and Creating Reusable Layouts Chevron down icon Chevron up icon
Chapter 3: Sourcing and Querying Data (from Anywhere!) Chevron down icon Chevron up icon
Chapter 4: Creating Reusable Templates Chevron down icon Chevron up icon
Chapter 5: Working with Images Chevron down icon Chevron up icon
Part 2: Going Live Chevron down icon Chevron up icon
Chapter 6: Improving Your Site's Search Engine Optimization Chevron down icon Chevron up icon
Chapter 7: Testing and Auditing Your Site Chevron down icon Chevron up icon
Chapter 8: Web Analytics and Performance Monitoring Chevron down icon Chevron up icon
Chapter 9: Deployment and Hosting Chevron down icon Chevron up icon
Part 3: Advanced Concepts Chevron down icon Chevron up icon
Chapter 10: Creating Gatsby Plugins Chevron down icon Chevron up icon
Chapter 11: Creating Authenticated Experiences Chevron down icon Chevron up icon
Chapter 12: Using Real-Time Data Chevron down icon Chevron up icon
Chapter 13: Internationalization and Localization Chevron down icon Chevron up icon
Other Books You May Enjoy Chevron down icon Chevron up icon

Customer reviews

Rating distribution
Full star icon Full star icon Full star icon Full star icon Half star icon 4.6
(5 Ratings)
5 star 80%
4 star 0%
3 star 20%
2 star 0%
1 star 0%
Purna Feb 11, 2022
Full star icon Full star icon Full star icon Full star icon Full star icon 5
I have enjoyed reading the first chapter. A brief history of Gatsby was discussed with good real-world examples to understand the importance of Gatsby and to get inspired. It has well-written step by step code examples to support the reader to build their website from scratch. The background details such as Gatsby development process is discussed in a beginner-friendly language. I highly recommend it to anyone interested in learning Gatsby.
Amazon Verified review Amazon
J.C. May 31, 2022
Full star icon Full star icon Full star icon Full star icon Full star icon 5
I've had this book for a couple of weeks and really enjoyed it. I've worked with React and Angular on different projects, but knew nothing about Gatsby. Turns out, it's a nice tool to streamline getting an entire website up and running. There are plenty of useful plugins, and it can even integrate with a CMS like WordPress.If you have any experience with React this book will make working with Gatsby easy. You'll be building a website as you work through each chapter, which I think is the best way to learn anything technical. I really liked that the book shows you everything you would need for a professional project.You'll cover the user interface, database, accessibility, SEO, analytics, authorization, hosting, and deployment. Even if you don't use Gatsby from day to day, the concepts covered here will still help you understand how to put together a full stack project.
Amazon Verified review Amazon
Ryan Feb 05, 2022
Full star icon Full star icon Full star icon Full star icon Full star icon 5
I've just finished reading the first 3 chapters and already I feel like I have learnt something new and I've been in web dev for 4 years now.It's written in a way that makes learning fun, it DOESN'T feel laborious, like a task, or like I'm reading documentation. And you are given access to all the resources to copy everything exactly on your own machine.It has everything you need to get up and running and gives you a massive head start to develop in the right way and somehow answers all your questions just as you start to wonder about them. If I was ever starting to wonder 'what if', then there was always an added note that covered it.Can't wait to finish reading it
Amazon Verified review Amazon
Matt Williamson Feb 27, 2022
Full star icon Full star icon Full star icon Full star icon Full star icon 5
I picked this book up to read the other day, and I'm glad that I did. I am a software engineer with 4 years of React experience and quite a bit of Gatsby experience as well. There are not many resources that can help with the full suite of things you can do with Gatsby. I mean, there are tutorials for everything that this book covers, but not in one place and not in the "correct" order.This book takes one through everything from getting started, to styling choices, to data sources, to SEO, to page analytics, to authentication, to deployment of a Gatsby site.Generally, the sections go through a topic with various issues surrounding that topic, then gives a suggestion on what people should do with their website. For instance, if you have been around React for a little while, you know how polarizing styling is. CSS in JSS? Stylesheets? Inline? Well, this book talks about the various ways of styling in Gatsby but then at the end, gives their advice on what you should do and why. Very opinionated but with very good reasons. I agreed with their reasoning and their choices throughout the book.The other thing that I love is that they also build a website throughout the book. I love that, because whenever I am learning something new, I have to build a thing in order to really learn the information. This is a great way to learn, and if one works through this book and this project, they'll be able to really build some awesome Gatsby websites!Note, I have received a copy of this book to review but I made the choice to review it.
Amazon Verified review Amazon
Hallo182 Mar 21, 2022
Full star icon Full star icon Full star icon Empty star icon Empty star icon 3
Ich mag den Autor dieses Buches, weshalb ich mir auch sein Buch besorgt habe.Bücher über neue Webtechnologien haben ja oft das Problem, dass sie schon bei Ihrer Veröffentlichung veraltet sind. Das ist hier, soweit ich bisher überblicken konnte, (noch) nicht der Fall.Das Buch ist in drei Kapitel unterteilt.1. Getting started (122 Seiten)2. Going live (74 Seiten)3. Advanced concepts (76 Seiten)Larsen-Disney versucht hier einen breit gefächerten Inhalt unterzubringen. Dadurch fehlt dem Buch (jedenfalls in den ersten zwei Kapiteln) der gewinnbringende Tiefgang. Den meisten Inhalt kann ich auch in der Dokumentation von Gatsby nachlesen, dafür brauche ich nicht das Buch. Mir fehlen irgendwelche Tipps, die so nicht in der Dokumentation stehen.Dementsprechend kann ich das Buch leider nicht empfehlen.
Amazon Verified review Amazon
Get free access to Packt library with over 7500+ books and video courses for 7 days!
Start Free Trial

FAQs

What is the delivery time and cost of print book? Chevron down icon Chevron up icon

Shipping Details

USA:

'

Economy: Delivery to most addresses in the US within 10-15 business days

Premium: Trackable Delivery to most addresses in the US within 3-8 business days

UK:

Economy: Delivery to most addresses in the U.K. within 7-9 business days.
Shipments are not trackable

Premium: Trackable delivery to most addresses in the U.K. within 3-4 business days!
Add one extra business day for deliveries to Northern Ireland and Scottish Highlands and islands

EU:

Premium: Trackable delivery to most EU destinations within 4-9 business days.

Australia:

Economy: Can deliver to P. O. Boxes and private residences.
Trackable service with delivery to addresses in Australia only.
Delivery time ranges from 7-9 business days for VIC and 8-10 business days for Interstate metro
Delivery time is up to 15 business days for remote areas of WA, NT & QLD.

Premium: Delivery to addresses in Australia only
Trackable delivery to most P. O. Boxes and private residences in Australia within 4-5 days based on the distance to a destination following dispatch.

India:

Premium: Delivery to most Indian addresses within 5-6 business days

Rest of the World:

Premium: Countries in the American continent: Trackable delivery to most countries within 4-7 business days

Asia:

Premium: Delivery to most Asian addresses within 5-9 business days

Disclaimer:
All orders received before 5 PM U.K time would start printing from the next business day. So the estimated delivery times start from the next day as well. Orders received after 5 PM U.K time (in our internal systems) on a business day or anytime on the weekend will begin printing the second to next business day. For example, an order placed at 11 AM today will begin printing tomorrow, whereas an order placed at 9 PM tonight will begin printing the day after tomorrow.


Unfortunately, due to several restrictions, we are unable to ship to the following countries:

  1. Afghanistan
  2. American Samoa
  3. Belarus
  4. Brunei Darussalam
  5. Central African Republic
  6. The Democratic Republic of Congo
  7. Eritrea
  8. Guinea-bissau
  9. Iran
  10. Lebanon
  11. Libiya Arab Jamahriya
  12. Somalia
  13. Sudan
  14. Russian Federation
  15. Syrian Arab Republic
  16. Ukraine
  17. Venezuela
What is custom duty/charge? Chevron down icon Chevron up icon

Customs duty are charges levied on goods when they cross international borders. It is a tax that is imposed on imported goods. These duties are charged by special authorities and bodies created by local governments and are meant to protect local industries, economies, and businesses.

Do I have to pay customs charges for the print book order? Chevron down icon Chevron up icon

The orders shipped to the countries that are listed under EU27 will not bear custom charges. They are paid by Packt as part of the order.

List of EU27 countries: www.gov.uk/eu-eea:

A custom duty or localized taxes may be applicable on the shipment and would be charged by the recipient country outside of the EU27 which should be paid by the customer and these duties are not included in the shipping charges been charged on the order.

How do I know my custom duty charges? Chevron down icon Chevron up icon

The amount of duty payable varies greatly depending on the imported goods, the country of origin and several other factors like the total invoice amount or dimensions like weight, and other such criteria applicable in your country.

For example:

  • If you live in Mexico, and the declared value of your ordered items is over $ 50, for you to receive a package, you will have to pay additional import tax of 19% which will be $ 9.50 to the courier service.
  • Whereas if you live in Turkey, and the declared value of your ordered items is over € 22, for you to receive a package, you will have to pay additional import tax of 18% which will be € 3.96 to the courier service.
How can I cancel my order? Chevron down icon Chevron up icon

Cancellation Policy for Published Printed Books:

You can cancel any order within 1 hour of placing the order. Simply contact [email protected] with your order details or payment transaction id. If your order has already started the shipment process, we will do our best to stop it. However, if it is already on the way to you then when you receive it, you can contact us at [email protected] using the returns and refund process.

Please understand that Packt Publishing cannot provide refunds or cancel any order except for the cases described in our Return Policy (i.e. Packt Publishing agrees to replace your printed book because it arrives damaged or material defect in book), Packt Publishing will not accept returns.

What is your returns and refunds policy? Chevron down icon Chevron up icon

Return Policy:

We want you to be happy with your purchase from Packtpub.com. We will not hassle you with returning print books to us. If the print book you receive from us is incorrect, damaged, doesn't work or is unacceptably late, please contact Customer Relations Team on [email protected] with the order number and issue details as explained below:

  1. If you ordered (eBook, Video or Print Book) incorrectly or accidentally, please contact Customer Relations Team on [email protected] within one hour of placing the order and we will replace/refund you the item cost.
  2. Sadly, if your eBook or Video file is faulty or a fault occurs during the eBook or Video being made available to you, i.e. during download then you should contact Customer Relations Team within 14 days of purchase on [email protected] who will be able to resolve this issue for you.
  3. You will have a choice of replacement or refund of the problem items.(damaged, defective or incorrect)
  4. Once Customer Care Team confirms that you will be refunded, you should receive the refund within 10 to 12 working days.
  5. If you are only requesting a refund of one book from a multiple order, then we will refund you the appropriate single item.
  6. Where the items were shipped under a free shipping offer, there will be no shipping costs to refund.

On the off chance your printed book arrives damaged, with book material defect, contact our Customer Relation Team on [email protected] within 14 days of receipt of the book with appropriate evidence of damage and we will work with you to secure a replacement copy, if necessary. Please note that each printed book you order from us is individually made by Packt's professional book-printing partner which is on a print-on-demand basis.

What tax is charged? Chevron down icon Chevron up icon

Currently, no tax is charged on the purchase of any print book (subject to change based on the laws and regulations). A localized VAT fee is charged only to our European and UK customers on eBooks, Video and subscriptions that they buy. GST is charged to Indian customers for eBooks and video purchases.

What payment methods can I use? Chevron down icon Chevron up icon

You can pay with the following card types:

  1. Visa Debit
  2. Visa Credit
  3. MasterCard
  4. PayPal
What is the delivery time and cost of print books? Chevron down icon Chevron up icon

Shipping Details

USA:

'

Economy: Delivery to most addresses in the US within 10-15 business days

Premium: Trackable Delivery to most addresses in the US within 3-8 business days

UK:

Economy: Delivery to most addresses in the U.K. within 7-9 business days.
Shipments are not trackable

Premium: Trackable delivery to most addresses in the U.K. within 3-4 business days!
Add one extra business day for deliveries to Northern Ireland and Scottish Highlands and islands

EU:

Premium: Trackable delivery to most EU destinations within 4-9 business days.

Australia:

Economy: Can deliver to P. O. Boxes and private residences.
Trackable service with delivery to addresses in Australia only.
Delivery time ranges from 7-9 business days for VIC and 8-10 business days for Interstate metro
Delivery time is up to 15 business days for remote areas of WA, NT & QLD.

Premium: Delivery to addresses in Australia only
Trackable delivery to most P. O. Boxes and private residences in Australia within 4-5 days based on the distance to a destination following dispatch.

India:

Premium: Delivery to most Indian addresses within 5-6 business days

Rest of the World:

Premium: Countries in the American continent: Trackable delivery to most countries within 4-7 business days

Asia:

Premium: Delivery to most Asian addresses within 5-9 business days

Disclaimer:
All orders received before 5 PM U.K time would start printing from the next business day. So the estimated delivery times start from the next day as well. Orders received after 5 PM U.K time (in our internal systems) on a business day or anytime on the weekend will begin printing the second to next business day. For example, an order placed at 11 AM today will begin printing tomorrow, whereas an order placed at 9 PM tonight will begin printing the day after tomorrow.


Unfortunately, due to several restrictions, we are unable to ship to the following countries:

  1. Afghanistan
  2. American Samoa
  3. Belarus
  4. Brunei Darussalam
  5. Central African Republic
  6. The Democratic Republic of Congo
  7. Eritrea
  8. Guinea-bissau
  9. Iran
  10. Lebanon
  11. Libiya Arab Jamahriya
  12. Somalia
  13. Sudan
  14. Russian Federation
  15. Syrian Arab Republic
  16. Ukraine
  17. Venezuela