How to Add Navigation in Gatsby
Gatsby provides you with a Link component. It performs faster at navigating between pages within your site than a tag. Therefore, you should use the a tag only for links that lead to other websites.
Creating Your Navigation
-
Create a
Navigationcomponent and make use of theLinkcomponent and itstoproperty// src/components/Navigation.js import React from 'react'; import { Link } from 'gatsby'; const Navigation = () => { return ( <nav> <ul> <li> <Link to="/"> Home </Link> </li> <li> <Link to="/about"> About </Link> </li> <li> <Link to="/contact"> Contact Us </Link> </li> </ul> </nav> ); }; export default Navigation; -
Use the
activeClassNameproperty to add a class to the currently active link. This example usesactivefor the class but you can name it whatever you want.// src/components/Navigation.js <li> <Link to="/" activeClassName="active"> Home </Link> </li> <li> <Link to="/about" activeClassName="active"> About </Link> </li> <li> <Link to="/contact" activeClassName="active"> Contact Us </Link> </li>Add some CSS styling to the
activeclass so that it stands out from the other links. This way the user can know which page they are currently on. -
(Optional) Create a
Layoutcomponent and include theNavigationcomponent in it// src/components/Layout.js import React from 'react'; import Navigation from './Navigation'; const Layout = ({ children }) => { return ( <> <Navigation /> <main>{children}</main> </> ); }; export default Layout; -
(Optional) Use the
Layoutcomponent in your pages// src/pages/about.js import React from 'react'; import Layout from '../components/Layout'; const About = () => { return ( <Layout> <h1>About Page</h1> </Layout> ); }; export default About;Repeat using the
Layoutcomponent in other pages that need to show the navigation.
Creating a Navigation With a Sub-menu
Sometimes a link in the navigation can have a sub-menu with other links. For example, you might have a “Products” link that shows a list of available product pages when you hover over it.
You can use the partiallyActive property to give the parent link an active class when a child route is open.
<nav>
<ul>
<li>
<Link
to="/products"
activeClassName="active"
partiallyActive={true}
>
Products
</Link>
<ul>
<li>
<Link to="/products/shirt">
Shirts
</Link>
</li>
<li>
<Link to="/products/pants">
Pants
</Link>
</li>
</ul>
</li>
</ul>
</nav>
The Products link will receive the active class when user opens a child route, for example Shirts.