Routing

How to do routing in Gatsby ?

Open your project in your favorite code editor.

gatsby folder structure

In your pages folder, index.js file refers to the home route in Gatsby it means (/).

If you create a new file in pages folder gatsby automatically creates the route.

Let’s create one.

Create a second.js file in your pages folder.

import React from "react"

function Second() {

        return (
            <div>
                <h1>Second page</h1>
            </div>
        )
    }

export default Second;

If you open localhost:8000/second you would see the second page.

In your index.js file import the gatsby-link.

import React from "react"
import Link from 'gatsby-link';

class Index extends React.Component{

    render() {
        return (
            <div>
                <h1>Home Page</h1>
                <Link to="/second">Second page</Link>
            </div>
        )
    }
}

export default Index;

It is a Link component provided by the Gatsby to means we need to refer the route.

In our pages folder, we already created a second.js file so that we added (/second).

routing gatsby