Now that you can create a new gatsby project let’s continues with a fundamental feature that gatsby has built in: Pages
A gatsby page is just a React component, but thanks to gatsby it will generate a page in our website. This means that if you create a page called “users.js” automatically gatsby will call that file when you go to the url /users in your development server.
Creating Gatsby Pages
If you open the project that we create in the previous post you will see a folder structure like this
1 2 3 4 5 6
/src /pages index.js /static ... # other files
In a first look is easy to assume that every time you need a new route/url in your website you need to create a react component inside the pages folder.
If you open the index.js you can see a simple React component, actually a FUNCTION component.
1 2 3
import React from"react";
exportdefault () => <div>Hello world!</div>;
I love arrow functions, but not this much so I will rewrite this component to something more fun (at least to me!)
Let’s go through this component, first we create an array called data, this array will contain the information about 3 people. The data was taken from the reqres.in API since we do not want to complicate things by involving async requests (yet!). After that we define a simple react component that will loop through the array and show the name, email and avatar of each customer. Ok with this information gatsby automatically will generate a /customers url for us. You do not need to restart the server, just go to your browser and open the following url:
1
http://localhost:8000/customers
You should see something like this:
Ok pretty cool, but we need a good way to navigate between the home/customer pages, let’s see how we can achieve that.
Navigating between Gastby pages
Gatsby has a special component called Link and it’s pretty useful to navigate between the pages without reload the whole page. Let’s create a navigation section for our website, first in our index page.
Now the website has a easy way to navigate between the pages
but repeating the same code in both pages does not feel very good and probably against the react philosophy. So let’s extract the navigation in a react component.
Creating and using React components in Gatsby
Since Gatsby use React under the hoods we can create our UI in tiny reusable components. Let’s create a component called TheNavBar. Since we do not want to gatsby turn this component into a page, let’s create a folder called components and inside of it the navbar.
Our folder structure will look like this:
1 2 3 4
src /components TheNavBar.js /pages
And our component:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
import React from"react"; import { Link } from"gatsby";