Getting Started with Gatsby.js: A Beginner’s Tutorial
- Install Gatsby CLI: To get started with Gatsby, you’ll need to install the Gatsby CLI. You can do this by running the following command in your terminal:
Copy codenpm install -g gatsby-cli
- Create a new Gatsby project: Once you have the Gatsby CLI installed, you can create a new Gatsby project by running the following command:
javascriptCopy codegatsby new my-gatsby-site
This will create a new directory named “my-gatsby-site” that contains a basic Gatsby project.
- Start the development server: Navigate into the “my-gatsby-site” directory and start the development server by running the following command:
bashCopy codecd my-gatsby-site
gatsby develop
This will start a local development server and you can view your Gatsby site in your browser at http://localhost:8000.
- Create a new page: In Gatsby, pages are React components that define the content of your website. To create a new page, create a new directory in the “src/pages” directory with the name of your page. For example, to create an “About” page, create a new directory named “about”. In this directory, create a new file named “index.js” and add the following code:
javascriptCopy codeimport React from "react"
const AboutPage = () => {
return (
<div>
<h1>About</h1>
<p>This is an example About page.</p>
</div>
)
}
export default AboutPage
- Add a navigation link: To add a navigation link to your new About page, open the “src/components/header.js” file and add the following code to the “Header” component:
javascriptCopy codeimport React from "react"
import { Link } from "gatsby"
const Header = () => {
return (
<header>
<nav>
<ul>
<li>
<Link to="/">Home</Link>
</li>
<li>
<Link to="/about">About</Link>
</li>
</ul>
</nav>
</header>
)
}
export default Header
- View the About page: Refresh your browser and you should now see a navigation link to your new About page.
This is a basic introduction to building a website with Gatsby.js. From here, you can continue to explore and build more complex pages and features for your website. Gatsby provides a rich ecosystem of plugins, templates, and tools that make it easy to build powerful and dynamic websites.