This article originally appeared on my blog.
Hey there! In the last couple lessons we covered what Next.js is and how to set up your first project. If you have read those guides, you are ready to learn about pages and routing. Fortunately, making routes and pages in Next.js is a snap to understand!
Let’s take a look at how routing works first.
Creating Routes and Pages
Routes
Creating your client-side pages in Next.js is wonderfully straightforward, thanks to its file-based routing system. You just need to know two concepts:
Your source code directory paths become your URL structure. For example, a file at
app/dashboard/settings/page.tsx
will appear in your browser athttp://myserver/dashboard/settings
.To make a URL accessible in your app, you must use a file named
page
within the appropriate directory. This file can end with.js
,.ts
,.jsx
, or.tsx
.
You can see this paradigm in action when you set up a new Next.js app. The screenshot below shows the index URL localhost:3000
is controlled by the index page app/page.tsx
.
As you might have guessed, you can nest these folders as deeply as you would like.
Here’s an example of a folder hierarchy that’s a few levels deep:
And here’s the corresponding browser page. The URL matches our folders above.
Pages
Once you have your route paths established, creating your page is as simple as exporting a React component from a page.jsx
or page.tsx
file:
export default function Page() {
return <h1>Hello, Dashboard Page!</h1>
}
Using Dynamic Segments
Dynamic segments allow you to capture variable segments from the URL. Create a folder somewhere in your directory path with brackets around its name to accept dynamic parts.
For example, app/settings/[username]/page.tsx
will yield a route that accepts any value for username
and incorporates it as an input parameter into the page’s component:
export default function Page({ params }: { params: { username: string } }) {
return <div>This is the settings page for {params.username}</div>
}
Linking and Navigating
You now understand the basic components of a Next.js app. How do you connect routes and pages together?
Basic Example
Next.js utilizes the Link
component from next/link
to enable client-side navigation between pages, ensuring that the transitions are quick and do not require a page reload. Here’s how you can link to the About page from, say, the homepage:
import Link from 'next/link';
const Home: React.FC = () => {
return (
<div>
Visit the <Link href="/about"><a>About Page</a></Link>.
</div>
);
}
export default Home;
Dynamic Segments
As a full-stack framework built on React, Next.js has full React support. Thus you can use all of the niceties of React, such as template literals and string interpolation, when coding for dynamic links.
// app/zoo/animals.jsx
import Link from 'next/link'
export default function ZooAnimals({ animals }) {
return (
<ul>
{animals.map((animal) => (
<li key={animal.id}>
<Link href={`/blog/${animal.species}`}>{animal.name}</Link>
</li>
))}
</ul>
)
}
Programmatic Routing
You can use Next’s built-in router to programmatically change pages (i.e. without user interaction). This can be especially useful in scenarios where you need to redirect a user after an action such as form submission or login.
Note that this is only available in client components, so you need to declare 'use client'
at the top of the file.
'use client'
import { useState } from 'react';
import { useRouter } from 'next/navigation';
export default function LoginForm({ username }: { username: string }) {
const router = useRouter();
const handleLogin = async (event: React.FormEvent) => {
event.preventDefault();
// Simulating a login process - replace with actual logic
const loginSuccessful = true;
if (loginSuccessful) {
router.push(`/profile/${username}`);
} else {
alert('Login failed!');
}
};
return (
<form onSubmit={handleLogin}>
<button type="submit">Login</button>
</form>
);
};
Conclusion
And there you have it — a thorough dive into the basics of pages and routing in Next.js! By now, you should feel comfortable creating static and dynamic routes, linking between pages seamlessly, and even navigating programmatically within your applications. These foundational skills are crucial to your understanding of Next.js.
In our next lesson, we'll push the boundaries further as we learn advanced page and routing techniques. Make sure to subscribe if you want to catch the next chapter as soon as it drops!
Top comments (0)