Use the <Link> component
In the last lesson we saw that state.router.link stores the current URL. We demonstrated this by manually changing the URL in the browser's address bar and saw how the URL in our <p> element changed as the component reacted to the data change.
In this lesson we will create a menu-based navigation to change the URL for us.
Frontity provides a number of useful components for us, amongst which is the <Link> component. The simplest way to use it is to just provide a link attribute with the URL as its value:
1
<Link link="/">Home</Link>
Copied!
We also provide the string that we want to be displayed as a clickable link. In the example above that is 'Home'.
The <Link> component simply outputs an <a> element into the resulting HTML, but without forcing a page reload which is what would occur if you simply added an <a> element instead of using the <Link> component.
1
<a href="/" target="_self">Home</a>
Copied!
Before we can use any of Frontity's built-in components we first need to import it. Frontity's built-in components are imported from @frontity/components.
So let's import the <Link> component into our root component file for use within our <Root> component. Let's add this import statement as the third line:
1
import Link from "@frontity/components/link"
Copied!
With that done we are now in a position to add a menu consisting of a <nav> element with three <Link> items as children. Using the example above as a template our index.js file can now look like this:
1
// File: /packages/my-first-theme/src/components/index.js
2
3
import React from "react"
4
import { connect } from "frontity"
5
import Link from "@frontity/components/link"
6
7
const Root = ({ state }) => {
8
return (
9
<>
10
<h1>Hello Frontity</h1>
11
<p>Current URL: {state.router.link}</p>
12
<nav>
13
<Link link="/">Home</Link>
14
<br />
15
<Link link="/page/2">More posts</Link>
16
<br />
17
<Link link="/about-us">About Us</Link>
18
</nav>
19
</>
20
)
21
}
22
23
export default connect(Root)
Copied!
When you save the file the browser should update and the menu will now be visible. Now if you click on the menu items you will see the URL in the browser's address bar change, and also the displayed value of state.router.link.
Here we've used the <Link> component in the simplest possible way. To learn more about what you can do with the <Link> component, including pre-fetching strategies to make your site more responsive, see this page in our documentation.
Check you're on the right track by comparing your changes with the ones in this commit.
Last modified 6mo ago
Copy link