What are the best ways to build static websites with Gatsby as well? (r) (r)

Dec 10, 2023

-sidebar-toc>

A demo site showing what you can build after reading this guide
Demo websites which demonstrate the potential of what you could create once you've read this tutorial.

Understanding static sites

  1. Performance: Static sites load fast since there isn't any server-side processing.
  2. Security Because there's no executable program on servers, static websites are more secure from threats in security.
  3. Scalability It's simple to share and save static websites through Content Delivery Networks (CDNs).
  4. Simplicity: They are easier to create, use and maintain.

After you have a better grasp of what static sites are and the benefits they provide, we can take a look at Gatsby.

What exactly is Gatsby?

  1. Rapidly Speedy: Gatsby improves the speed of your website for speed by employing techniques such as code splitting and lazy loading. This leads to faster loading of your pages.
  2. Flexible data sourcing: It can get data from a variety of sources including Markdown files databases, APIs and more.
  3. Rich Plug-in Ecosystem Gatsby's vast ecosystem of plug-ins allows you to extend the capabilities of your application quickly.
  4. SEO and performance: Gatsby automatically produces optimized HTML that is better suited to SEO and to be more efficient.

Starting to Begin with Gatsby

To be able to comply to this instruction You must have:

  • Basic knowledge of HTML, CSS, and JavaScript
  • Basic knowledge of React

If you want to start at Gatsby and create a strategy, review one of the hundreds of examples available in Gatsby Starter Library. Gatsby Starter Library as well as create an start-up project and work through it to completion.

For this, let's take advantage of GatsbyJS's Hello World starter for GatsbyJS as it gives us an easy-to-use project that isn't bundled with extensions or additional documents.

  1. Before you begin, download Gatsby's CLI on your PC by following the below instruction:
NPM install –g gatsby cli

Run the version gatsby to verify whether or not the installation succeeded.

  1. Next, navigate into the directory you want to create your project in, and run the following command:
npx gatsby new https://github.com/gatsbyjs/gatsby-starter-hello-world

Modify the project-name> above to reflect your project's title. you're working on.

  1. Once this is completed After that, go to the project folder and then start the server for development.
Cd gatsby - create

The local development server will start at http://localhost:8000, where you can access your Gatsby site.

The Gatsby hello world theme
The Gatsby Hello World theme.

Learning Gatsby File Structure

When you open the project by using an editor that works with code, you'll see the following structure:

/ |-- /public |-- /src |-- /pages |-- index.js |-- /static |-- gatsby-config.js
  • Public: This directory contains the results of your Gatsby method of making. The directory is where the developed HTML, CSS, JavaScript and other information files are saved.
  • (or SRC): This is the center in the Gatsby project. It's where you'll be required to devote the majority time of your day. There are numerous subdirectories along with files:
  • /pages: This is where every page for your website are stored. Every JavaScript document in this folder is linked to the location you've chosen for your site.
  • static This folder is utilized for static files needed to be added to your website. These include images, fonts or downloadable documents. The files are offered as is and not processed by Gatsby.
  • gatsby-config.js: This configuration file lets you specify various settings for your Gatsby site. You can specify plugins or metadata that you want to include on your site with various settings.

The Making of Pages and Components

In Gatsby creating web pages is an easy process. Each JavaScript files you make in the pages/src directory is automatically transformed into a page using the appropriate route, thanks to Gatsby's automated pages generation.

It is possible to build the pages that you need on your site by the inclusion of other JavaScript documents to pages. These files are located in the pages folder inside the /src/pages folder. For instance, you can create the about.js file for the "About" page.

Although you can create distinct JavaScript files for each page directly within pages/src/pages folder, you can also create subfolders to each page pages/src/pages folder, you are capable of organizing the pages you have created in a distinct method. You can create subfolders to distinct pages. If you do this, for example, you could make the blog folder that will organize each blog-related web page.

In this case, it is the way that the page structure will look as follows:

|-- /src |-- /pages |-- about.js |-- index.js |-- /blog |-- index.js

Utilizing JSX for Pages

In this case, you could design the content on your homepage page ( index.js) using the following steps:

Import React from'react";the standard method for exporting React is home() returning ( Enjoy static site hosting Through StSH. Quick, Secure and Reliable Hosting Solution. > );

To create a hyperlink to other websites, you could employ this Link feature. This is how:

integrate React into react import Link from the 'gatsby' default function export default function for return() return ( Find Static Website Hosting with StSH. Rapid, secure and reliable Hosting Solutions. to="/about">About Us to="/blog">Blog > );

In this instance in the above illustration, we've imported Link elements that we found on the gatsby website and used it to create links for Our "About Us" page and our blog. The "About Us" page, as an instance, we have the link about. When users click on"About Us," like"About Us," click the "About Us" button, they are directed into"About Us" page/about page.

To create links to external sites, use normal anchor ( ) tags with attribute called HREF: attribute:

Import React using'react";Export the default home functions() return ( Get Static Site Hosting With StSH. Rapid, secure, and reliable Hosting solution. Benefit from static website hosting using StSH. Rapid, secure, and reliable Hosting solution. Discover more on );

In this instance it opens an external site within a completely different browser window as it can make use of attributes like target="_blank" and rel="noreferrer" attributes.

The production of components for Gatsby

Gatsby's modular design allows users to build reusable elements to your website. Instead of duplicated codes across many pages, you're in a position to encapsulate the components you use in your everyday work into parts which makes your code base more flexible, manageable, and efficient.

If the code you employ to display your website's homepage has the navigational section as the primary content as well as the footer

Import React with the help of'react Import Link from 'gatsby' export default function default function for home() return ("home" back to ="/">Home to="/about">About to="/blog">Blog Make advantage of Static web hosting with StSH. Fast, secure and reliable Hosting Solution. Read more Hosted with by 's' ' href="https://.com/static-site-hosting"> Static Site Hosting . > );

Imagine having to copy the footer and navigation bar codes for each page on your site. Components can come in. They can be created as reusable components which can be utilized to create the footer, navigation bar or any other part of code that could be employed across various elements and web pages.

To be able to utilize components from Gatsby in order to make use of these elements, you need to create folders for components in Gatsby. Set up components folders within Gatsby. In Gatsby, create an component folder in the src folder. It will contain all the components. Next, create your components, e.g. Navbar.js and Footer.js. Within the Navbar.js file, split the code up in the following format:

Import Link 'gatsby' import React using'react";const navigationbar () = return ( Home About Blog ) Export default Navbar

Additionally, Footer.js:

import React from 'react'; const Footer = () => return ( Hosted with by 's' ' href="https://.com/static-site-hosting">Static Site Hosting . ); ; export default Footer;

It is then possible to add documents to pages or component and then use this process:

import React from 'react'; import Navbar from '../components/Navbar'; import Footer from '../components/Footer'; export default function Home() return ( Enjoy Static Site Hosting With StSH. Rapid, secure, and reliable Hosting Solution. Discover more regarding );

Layout components and design

The most popular method of conducting the creation of websites is the creation of an layout component that reflects the overall design of the website. The layout component usually includes elements that appear on each page, like the header, footer and sidebars, navigation menus, and so on.

Make a new file called Layout.js in your component's components/src/components directory. Then, you can identify the layout's design. This guide will define that layout's style must include the footer, and the navigation bar

import React from 'react'; import Navbar from './Navbar'; import Footer from './Footer'; const Layout = ( children ) => return ( className="content">children ); ; export default Layout;

When this layout component can be used to create the components to wrap the contents of pages (provided by the children). If you wish to use the layout component within your pages, you have to install it, and then use it to wrap the contents of your pages it. In this case, for example, page index.js page:

import React from 'react'; import Layout from '../components/Layout'; export default function Home() return ( Enjoy Static Site Hosting With StSH. Fast, safe and reliable Hosting solution. Learn more );

The use of a layout feature can ensure you've got a the same layout and style across your pages as well as keeping your codes organized and as up-to-date. This is a fantastic method to handle the elements that are most commonly used on your website efficiently.

Styling Pages as well as other elements in Gatsby

The style you choose for your Gatsby website can be flexible as it allows you to utilize different strategies, including basic CSS and CSS-in JS, as well as CSS preprocessors, such as Sass. We'll show you how to make simple and Mod-styled websites.

CSS Styling

In Gatsby there's a way to build a CSS file. Then, you can link it to any website or component you'd like it to be linked to, and it should be flawlessly functioning. For example, you could create an the styles folder inside the folder called src folder, and then create global.css. global.css file with the CSS code.

Here are some of the most popular styles of parts that were developed earlier:

@import url('https://fonts.googleapis.com/css2?family=Poppins:wght@300;400;500&display=swap'); * margin: 0; padding: 0; box-sizing: border-box; body background-color: #ddd; font-family: 'Poppins', sans-serif; width: 1200px; margin: 0 auto; a text-decoration: none; img width: 100%; nav display: flex; justify-content: space-between; height: 200px; align-items: center; nav .logo-img width: 100px; nav .nav-links a padding: 0 20px; font-size: 18px; @media (max-width:700px) body width: 100%; padding: 0 20px; nav .nav-links a padding: 0 18px; .footer width: 100%; text-align: center; margin: 100px 0 20px; 

You can then include your CSS file into the components which you want to style. This is the case, and you are able to add it to your Layout component, ensuring that it's applied to every component.

import React from 'react'; import Navbar from './Navbar'; import Footer from './Footer'; import '../styles/global.css'; const Layout = ( children ) => return ( className="content">children ); ; export default Layout;

Module CSS Styling

CSS Modules let you scope your styles to specific elements or even webpages. This helps avoid clashes between styles, as well as making it simpler to control your CSS code. In the styles folder, create your CSS modules with the structure (pageName>.module.css and add the specific style into the files.

In this case, you can create home.module.css for the homepage and then add the following code:

.home_hero display: flex; justify-content: center; align-items: center; flex-direction: column; text-align: center; .home_hero h1 font-size: 60px; width: 70%; .home_hero p color: #6E7076; font-size: 20px; .btn background-color: #5333ed; padding: 20px 30px; margin-top: 40px; border-radius: 5px; color: #fff; @media (max-width:700px) .home_hero h1 font-size: 40px; .home_hero p font-size: 16px; 

To use module CSS styles on your Gatsby site or any other component to use the CSS module you need to load the CSS style styles of the CSS module in the form of an object on the top of the page or file before using it in the following ways:

import React from 'react'; import Layout from '../components/Layout'; import * as styles from '../styles/home.module.css'; export default function Home() return ( Enjoy Static Site Hosting With StSH. Fast, Secure, Reliable Hosting Solution. Read more );

Making use of Static Files in Gatsby

For Gatsby static files refer to the assets such as images, fonts, and CSS files, as well as various other files which are directly sent to the client's web browser with no need to use server-side processing. The files are then added to the static directory within the root directory of your project.

As an example, if for instance you post your picture -logo.png to the directory located in the static directory, it will show on your component the way it is:

link import from 'gatsby' React from 'react';const the Navbar () = return ( home to ="/"> home to ="/">Home to="/about">About to="/blog">Blog ) Export default Navbar

Gatsby will convert these relative pathways to the appropriate URL when your website has been built. In this course, you will learn how to optimize images within Gatsby.

Integrations and plugins

Gatsby provides a variety of plugins that allow you to enhance the functionality of. The plugins can aid in SEO, analytics images, markdown optimization, photo transformation and more. Setting up and installing the plugins is easy and can significantly increase the performance of your website.

In this tutorial video we will make use of four plug-ins

  1. gatsby-transformer-remark: This plugin allows you to transform Markdown files into HTML content, making it easy to create and manage blog posts, documentation, or any text-based content.
  2. gatsby-transformer-sharp and gatsby-plugin-sharp: These plugins work together to optimize and manipulate images in your Gatsby project.
  3. gatsby-source-filesystem: This plugin enables you to source files from your project directory and make them available to query with GraphQL.

For installing these plugins within your Gatsby project, execute this command inside the root directory of the project to perform installation:

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

Then, you can edit them inside the gatsby-config.js file. This is an example of how you can configure plug-ins

module.exports = plugins: [ // ...other plugins // Transform Markdown files into HTML 'gatsby-transformer-remark', // Optimize and manipulate images 'gatsby-transformer-sharp', 'gatsby-plugin-sharp', // Source files from your project directory resolve: `gatsby-source-filesystem`, options: name: `posts`, path: `$__dirname/src/posts/`, , , resolve: `gatsby-source-filesystem`, options: name: `images`, path: `$__dirname/src/images/`, , , ], ;

Two gatsby-source-filesystem configurations are created, pointing to two folders: posts and images. Posts will store some markdown files (blog posts) that would be transformed with gatsby-transformer-remark, and images will store images for the blog and other images you wish to optimize.

Be sure to reboot your local development server every whenever you alter your gatsby-config.js file.

Creating Blog Posts

Once you've installed the plugins make posts folders within the post folder within the Src directory. After that, make two Markdown documents with the following contents:

post-1.md:

--- title: "Introduction to Gatsby" date: "2023-10-01" slug: "introduction-to-gatsby" description: "Learn the basics of Gatsby and its features." featureImg: ../images/featured/image-1.jpeg --- Welcome to the world of Gatsby! In this post, we'll take you through the basic concepts of Gatsby and its clever features.

Additionally, post-2.md:

--- title: "Optimizing Images in Gatsby" date: "2023-10-05" slug: "optimizing-images-in-gatsby" description: "Explore how to optimize images in your Gatsby project." featureImg: ../images/featured/image-2.jpeg --- Images play a crucial role in web development. In this blog we'll look at how to optimize images on Gatsby using plugins.

They are Markdown files contain metadata and front matter to blog post content, such as names and dates, as along with slugs, descriptions and images.

To query Gatsby, GraphQL can query the Gatsby novel.

When you run gatsby develop in your terminal, you'll notice that, in addition to the link gatsby-source-filesystem, which opens your project on the web, you also see the http://localhost:8000/___graphql URL. The link will allow you an access point to GraphiQL Editor that you could make use of to develop your own Gatsby project.

When you open the editor, you will get the following user interface

The Gatsby GraphiQL playground
Gatsby GraphiQL is the Gatsby GraphiQL play area.

You'll be able to get the greatest information about your website from this editor. The reason is that you've developed markdown files and made the necessary adjustments in your gatsby-config.js file. It's possible to search markdown files and their content. Markdown files and their content with the below query inside the editor.

blogList query *

The query extracts information from every Markdown documents by employing the AllMarkdownRemark. It extracts details such as that of the name, slug as well as the descriptions from the top of every Markdown document, as well as their ID.

After you've written your query make sure you click the button after writing your query then press"Play" "Play" button (a right-facing triangle) to run the query. Results will be displayed at the top-right of the editor.

Using the GraphiQL playground to get markdown information
Utilizing the GraphiQL playground to collect the markdown details.

You can then employ GraphQL to access the Markdown data in the pages of your component. To access this information blog/index.js or the blog/index.js page, first install graphql by using the gatsby application. In the final line of your JSX code, include the following details:

export const query = graphql` query BlogList allMarkdownRemark nodes frontmatter title slug description id `;

The above code uses this graphql tag to create the GraphQL query. The term GraphQL is used to refer to the name of queries. What you're adding to your blog/index.js file should be looking like is in the format below:

import graphql, Link from 'gatsby'; import React from 'react'; import Layout from '../../components/Layout'; import * as styles from '../../styles/blog.module.css'; const blog = ( data ) => const posts = data.allMarkdownRemark.nodes; return ( Blog posts.map((post) => ( post.frontmatter.title post.frontmatter.description )) ); ; export default blog; export const query = graphql` query BlogList allMarkdownRemark nodes frontmatter title slug description id `;

In the example code in the previous code in the above code, you use query results using the information prop inside the component. After that, you scan the content's data with you JavaScript method. After that, you will be able to display each post's title in an arrangement.

To avoid errors, create to avoid errors, create a blog.module.css file in the styles folder. After that, you can add the below code:

.blog_cont h2 font-size: 40px; margin-bottom: 20px; .blog_grid display: grid; grid-template-columns: 1fr 1fr 1fr; gap: 20px; @media (max-width:700px) .blog_grid grid-template-columns: 1fr; .blog_card background-color: #bfbfbf; padding: 20px; border-radius: 5px; color: #000; transition: all .5s ease-in-out; .blog_card:hover background-color: #5333ed; color: #fff; .blog_card h3 margin-bottom: 15px; .blog_card p margin-bottom: 15px; 
Display of blog posts fetched via GraphQL
Blog post posts displayed via GraphQL.

Lerner's Templates, as well as making dynamic pages in Gatsby by using GraphQL

in Gatsby the Gatsby, templates and dynamic websites are the primary concepts that allow you to create dynamic and flexible websites that are driven by data. Templates allow you to define the style and layout of your web pages. GraphQL helps you to gather information to fill the templates in a way that is automatic.

The creation of a template to use to be used for Blog Posts

Imagine that you wish to start a blog in which every blog post has identical in its structure and contains an introduction and a description. Create an BlogDetails template to create this style. Within the the src folder, you will be able to build an Template folder. Then, create blog-details.js file: blog-details.js file:

import React from 'react'; import Layout from '../components/Layout'; import * as styles from '../styles/blog-details.module.css'; const BlogDetails = () => return ( Title className=styles.html dangerouslySetInnerHTML= /> ); ; export default BlogDetails; In this instance, the BlogDetails template defines the format for blog post. Next, let's utilize GraphQL to pull information from specific blog posts to pass as props to the template. To create dynamic pages to build dynamic websites, you need to build the gatsby-node.js file inside the root directory of your project. The file allows users to define how the pages are made. The gatsby-node.js file, utilize GraphQL to retrieve the information which you would like to utilize for dynamic websites. In the case of, for instance, if you've Markdown blog posts, you can query their slugs: const path = require(`path`); exports.createPages = async ( graphql, actions ) => const data = await graphql(` query Articles allMarkdownRemark nodes frontmatter slug `); data.allMarkdownRemark.nodes.forEach((node) => actions.createPage( path: '/blog/' + node.frontmatter.slug, component: path.resolve('./src/templates/blog-details.js'), context: slug: node.frontmatter.slug , ); ); ; In this example in this example, we search the slugs for all Markdown posts and create dynamic pages for each article making use of this BlogDetails template. The context object may be utilized to provide data in the form of data to the template. The data (slug) is what the template utilizes to gather other data that's aligned with the data within the slug. It is important to understand the process of image optimization in Gatsby before adding the GraphQL query to the template's website. Image Optimization in Gatsby Earlier, you installed and configured the gatsby-transformer-sharp and gatsby-plugin-sharp along with gatsby-source-filesystem for sourcing images. With these plugins, it is possible to optimize and query images with GraphQL. Here's an example of how to query and display an optimized image using the gatsby plugin-sharp: export const query = graphql` query file(relativePath: eq: "example.jpg" ) childImageSharp fluid ...GatsbyImageSharpFluid `; In the code above in the above code, you're requesting an image named example.jpg from the images source and then using the fluid property of the image to show it in a the most responsive and optimized rendering. Then, you can use images-gatsby to load the image for images that are optimized. import React from 'react'; import graphql from 'gatsby'; import Img from 'gatsby-image'; const ImageExample = ( data ) => const fluid = data.file.childImageSharp; return ( ); ; export default ImageExample; Queuing Dynamic Pages Gatsby is using the template to build distinct pages for every blog post. Let's now include a GraphQL query on the template page to fetch the relevant data, based on the URL: import graphql from 'gatsby'; import Img from 'gatsby-image'; import React from 'react'; import Layout from '../components/Layout'; import * as styles from '../styles/blog-details.module.css'; const BlogDetails = ( data ) => const html = data.markdownRemark; const title, featureImg = data.markdownRemark.frontmatter; return ( title ); ; export default BlogDetails; export const query = graphql` query ProjectDetails($slug: String) markdownRemark(frontmatter: slug: eq: $slug ) html frontmatter title featureImg childImageSharp fluid ...GatsbyImageSharpFluid `; In the above code, you will notice it is querying for the optimized image and querying for the blog entry that matches the slug. Find the full source codes for Gatsby on GitHub. Gatsby project at GitHub. Install Gatsby static websites Once you've finished the repo, you can follow these steps for installing your static website: Sign into your account or sign up in order to view the dashboard of your My Dashboard. Authorize the Git account through your service provider. Select Static Sites in the right sidebar and choose Add Site. Add Site. Choose the repository that you wish to be deployed from, as well as the branch you want to use for deployment to. Assign a unique name to your site. My will detect the build parameters that are utilized by the Gatsby project and automatically. You will see the below settings already in place for you to use: Build command npm run build Node version: 18.16.0 Publishing directory: public Click on the Make an choice.. Summary The book covers the essential concepts of routing and data source, as well as the appearance of images, as well as the image optimization plugins, deployment and more. Gatsby's versatility, performance and wide-ranging ecosystem make it a great choice for build static websites. If you're planning to create a personal blog, portfolio or even a corporate website, Gatsby has you covered. Now it's time to put that skills to use and create your own Gatsby site. Did you utilize Gatsby in the building of something? Do not hesitate to discuss your experience and ideas with us via the comments in the form below. Joel Olawanle Joel is an Frontend developer at the company the Technical Issues Editor position. Issues. He is a passionate educator with a love of the open-source software. He has published more than 200 technical articles, mainly about JavaScript and the frameworks that it utilizes. Website LinkedIn Twitter

This article was originally posted here

This post was first seen on here