Gatsby — Static Site Generator For React — Introduction
By: Sebastian Eschweiler
Tags: Front End Development, Gatsbyjs, Reactjs, Web Development, React

This post has been published first on CodingTheSmartWay.com.

Subscribe On YouTube

Gatsby is a static site generator for React and has just been released (version 1.0). This tutorial will take a look at this new project and show you how to install Gatsby and develop & deploy your first website.

Gatsby has lots of advantages:

Automatic routing based on your directory structure. No need to include additional code for configuring the router

HTML code is generated server-side

Pre-configured Webpack-based build system

Easily extensible by plugin ecosystem

Optimized for speed. Gatsby loads only critical parts so that your site loads as fast as possible. Once loaded, Gatsby prefetches resources for other pages so that clicking around the site feels incredible fast.

Easy data integration from sources like CMSs, SaaS services, APIs, databases, file system

Installing Gatsby

The installation of Gatsby is done by using the Node.js Package Manager on the command line. Simply execute the following command to install the React static site generator globally on your system:

$ npm install --global gatsby-cli

Having completed the installation procedure the Gatsby CLI is available with command gatsby. Now we’re ready to initiate a new Gatsby project by using the command in the following way:

$ gatsby new my-gatsby-site

You’ll receive the following output on the command line:

Now we’re able to change into the newly created project directory my-gatsby-site and start up the live-reload development web server by using command:

$ gatsby develop

This will open up the default Gatsby site in the browser:

The application consist of two pages. You can use the link Go to page 2 to open the second page:

The Gatsby development web server comes with live reloading capabilities. This means that you can make changes to the course code will cause a hot reload of the affecting elements in the browser. You will be able to see the effect of changes immediately without the need of manually reloading the side.

Discovering The Project Structure

Now that you have set up and run the first Gatsby project successfully we can take a look at the project structure. Just open up the project folder in your code editor of choice (in the following Visual Studio Code is used).

Here you can see the structure of the project:

The main implementation parts can be found within the src folder. If you take a look inside that folder you’ll find two more folders inside:

layouts

pages

The layouts folder contains the two files index.js and index.css. In index.js you can find the starting point of the React application, the layout component:

import React from 'react'

import PropTypes from 'prop-types'

import Link from 'gatsby-link'

import Helmet from 'react-helmet' import './index.css' const Header = () => (

<div

style={{

background: 'rebeccapurple',

marginBottom: '1.45rem',

}}

>

<div

style={{

margin: '0 auto',

maxWidth: 960,

padding: '1.45rem 1.0875rem',

}}

>

<h1 style={{ margin: 0 }}>

<Link

to="/"

style={{

color: 'white',

textDecoration: 'none',

}}

>

Gatsby

</Link>

</h1>

</div>

</div>

) const TemplateWrapper = ({ children }) => (

<div>

<Helmet

title="Gatsby Default Starter"

meta={[

{ name: 'description', content: 'Sample' },

{ name: 'keywords', content: 'sample, something' },

]}

/>

<Header />

<div

style={{

margin: '0 auto',

maxWidth: 960,

padding: '0px 1.0875rem 1.45rem',

paddingTop: 0,

}}

>

{children()}

</div>

</div>

) TemplateWrapper.propTypes = {

children: PropTypes.func,

} export default TemplateWrapper

This file consist of two component implementations: Header and TemplateWrapper. TemplateWrapper is the layout component of our Gatsby application and makes use of Header component.

The react-helmet library is used to attach header information to the HTML site which is generated by the JSX template code of TemplateWrapper.

The layout component is a special Gatsby component which has one prop: children. Please note that children is a function which needs to be executed within the JSX code to indicate the exact location where the HTML output of child components must be inserted.

The layout component is a container with the wrapper code which is displayed for every page in your Gatsby application. This means that the layout component can be used for displaying a navigation menu or a footer area for example.

The default Gatsby starter template application consists of multiple pages. For each page you will be able to find a separate JavaScript file in the pages folder.

The implementation of the main application page is available in pages/index.js:

import React from 'react'

import Link from 'gatsby-link' const IndexPage = () => (

<div>

<h1>Hi people</h1>

<p>Welcome to your new Gatsby site.</p>

<p>Now go build something great.</p>

<Link to="/page-2/">Go to page 2</Link>

</div>

) export default IndexPage

The React component which is implemented here is named IndexPage and only containing the JSX template code which is needed to generate the HTML output of that component.

Furthermore the Link component is imported from the gatsby-link package and used within the JSX code to generate a link to SecondPage component.

The implementation of SecondPage is available in file pages/page-2.js:

import React from 'react'

import Link from 'gatsby-link' const SecondPage = () => (

<div>

<h1>Hi from the second page</h1>

<p>Welcome to page 2</p>

<Link to="/">Go back to the homepage</Link>

</div>

) export default SecondPage

The implementation looks quite similar to IndexPage. This time a Link to IndexPage is added to the component’s output by using the Link component in the following way:

<Link to="/">Go back to the homepage</Link>

The last file you can find in the pages folder is named 404.js. This is the page component which is used if a user tries to access a path which is not existing:

import React from 'react' const NotFoundPage = () => (

<div>

<h1>NOT FOUND</h1>

<p>You just hit a route that doesn't exist... the sadness.</p>

</div>

) export default NotFoundPage

Finally there is a special Gatsby configuration file: gatsby-config.json

module.exports = {

siteMetadata: {

title: `Gatsby Default Starter`,

},

plugins: [`gatsby-plugin-react-helmet`],

}

Inside the configuration file you can find a configuration property named plugins. This property gets assign an array which is including a list of Gatsby plugins which should be made available to the application. By default the plugin gatsby-plugin-react-helmet is installed. If you’d like to install further Gatsby plugins you can browse through the list of available plugins at https://www.gatsbyjs.org/docs/plugins/. You can install any of those plugins by installing the plugin via NPM first:

$ npm install --save [plugin-name]

And next add the plugin name to the array which is assigned to the plugins property in gatsby-config.json.

Extending The Default Project

Now that you have a sound understanding of the default building blocks in the project we can move on and see how we can extend the implementation.

Let’s add a new page to our project by creating the new file src/pages/page-3.js and insert the following code:

import React from 'react' class ThirdPage extends React.Component{ constructor() {

super()

this.state = { count: 0 }

} render() {

return(

<div>

<h1>Page 3</h1>

<p>Count: {this.state.count}</p>

<button onClick={() => this.setState({count: this.state.count + 1})}>+</button>

<button onClick={() => this.setState({count: this.state.count - 1})}>-</button>

</div>

)

}

} export default ThirdPage

The new page is implemented as a standard React component. The output of this component is interactive. A state property count is defined and the user is able to increment and decrement this state value. Open the page by using URL http://localhost:8000/page-3 in the browser. The result should now correspond to the following screenshot:

Now we have a working React.js counter inside our static website.

To make it more easier to access the three pages of our application let’s introduce a navigation menu in the header section. Open up file src/layouts/index.html and adapt the JSX code of Header component:

const Header = () => ( [...] <h1 style={{ margin: 0 }}>

<Link

to="/"

style={{

color: 'white',

textDecoration: 'none',

}}

>

Gatsby

</Link> <ul style={{ listStyle: 'none', float: 'right'}}>

<li style={{ display: 'inline-block', marginRight: '1rem'}}><Link style={{color: 'white', textDecoration: 'none', fontSize: 'x-large'}} to="/">Home</Link></li>

<li style={{ display: 'inline-block', marginRight: '1rem'}}><Link style={{color: 'white', textDecoration: 'none', fontSize: 'x-large'}} to="/page-2">Page 2</Link></li>

<li style={{ display: 'inline-block', marginRight: '1rem'}}><Link style={{color: 'white', textDecoration: 'none', fontSize: 'x-large'}} to="/page-3">Page 3</Link></li>

</ul>

</h1>

</div>

</div>

)

The output now changes to the following:

The menu on top can now be used to switch between the three pages quickly.

Deployment

As Gatsby is generating static content the deployment of a site is very easy. You can choose any static file hoster. For the following example let us use surge.sh. This service offers static file hosting for free which can be controlled command line. First let’s build the Gatsby project for production by using the following command:

$ gatsby build

This command is generating the static content. All files are saved in the public folder. To deploy to surge.sh, first install the surge.sh command line interface via NPM:

$ npm install --global surge

Next you can make use of the surge command to deploy the content of the public folder:

$ surge public/

This post has been published first on CodingTheSmartWay.com.