In this tutorial, we will be learning about basic routing in Next.js. Routing is the system that matches URLs to views and templates. It is a critical part of any web application and Next.js provides a simple, yet powerful, solution for it.
By the end of this tutorial, you will:
To follow along, you should have a basic understanding of:
Next.js follows a file-system based routing mechanism under the pages
directory. Each file corresponds to a route with the same name. For example, if you create a file named about.js
in the pages
directory, then you will be able to access it at http://localhost:3000/about
.
Let's create a simple Next.js application with two pages, Home and About.
pages/index.js
)// Import the Link API from next/link
import Link from 'next/link';
function Home() {
return (
<div>
<h1>Home Page</h1>
{/* Link to the about page */}
<Link href="/about">
<a>About</a>
</Link>
</div>
);
}
export default Home;
In the code above:
next/link
which allows us to create links that navigate between pages.Link
component to link to the About page. The href
prop is the path to the page we want to navigate to.pages/about.js
)// Import the Link API from next/link
import Link from 'next/link';
function About() {
return (
<div>
<h1>About Page</h1>
{/* Link to the home page */}
<Link href="/">
<a>Home</a>
</Link>
</div>
);
}
export default About;
In the About page, we have a similar setup as the Home page, but with a link back to the Home page.
In this tutorial, we've covered the basics of routing in Next.js. We've learned how to create pages and navigate between them using the Link
component from next/link
.
To continue learning about routing in Next.js, you could explore:
contact.js
and add a link to it on the Home page.contact.js
in the pages
directory with similar content as the previous examples.Add a new Link
component on the Home page with href="/contact"
.
Exercise: Create a dynamic route that displays a user's profile based on their username.
Solution:
[username].js
in the pages
directory.Access the username from the route parameters using router.query.username
.
Exercise: Programmatically navigate to the About page when a button is clicked.
Solution:
useRouter
hook from next/router
.router.push('/about')
when the button is clicked.Remember to practice regularly and try different things to get the most out of your learning experience. Happy coding!