In this tutorial, we will explore how to pass data between routes in Next.js, a popular React framework. We will learn how to send data from one route to another using different methods like query parameters and dynamic route segments.
By the end of this tutorial, you will be able to:
Prerequisites
Concepts
pages
directory becomes a route.pages
directory.Passing data using query parameters
Suppose we have a route /user
and we want to pass the user's name to this route. We can do this using query parameters.
Below is an example of how to link to the /user
route with a query parameter:
```jsx
import Link from 'next/link'
function HomePage() {
return (
export default HomePage
```
In the /user
route, we can access the name passed in the query parameter like this:
```jsx
import { useRouter } from 'next/router'
function UserPage() {
const router = useRouter()
return (
Welcome, {router.query.name}
export default UserPage
```
When we click on the "Go to user's page" link, we'll be directed to the /user
route and the webpage will display "Welcome, John".
Passing data using dynamic route segments
Suppose we have a blog and each blog post has a unique id. We can use a dynamic route to display each blog post.
First, we create a file called [id].js
in the pages/posts
directory. The [id]
part in the filename is the dynamic route segment.
```jsx
import { useRouter } from 'next/router'
function PostPage() {
const router = useRouter()
return (
You are viewing post {router.query.id}
export default PostPage
```
Now, we can link to any post by using its id in the URL. For example, if we link to /posts/42
, the webpage will display "You are viewing post 42".
In this tutorial, we have learned how to pass data between routes in Next.js using query parameters and dynamic route segments. This is a crucial aspect of building dynamic and interactive web applications.
For further learning, you can explore:
getServerSideProps
or getStaticProps
.Create a blog with Next.js. Each blog post should have a unique route based on its id. Display the blog post's id on its page.
Create a user page that displays a user's name. Pass the user's name to the page using a query parameter.
Create a product page that displays a product's name and id. Pass the product's name and id to the page using dynamic route segments and query parameters.
Remember, practice is key when learning new concepts in web development. Happy coding!