0
0
NextJSframework~30 mins

Programmatic navigation (useRouter) in NextJS - Mini Project: Build & Apply

Choose your learning style9 modes available
Programmatic Navigation with useRouter in Next.js
📖 Scenario: You are building a simple Next.js app with two pages: a homepage and a profile page. You want to add a button on the homepage that takes the user to the profile page when clicked.
🎯 Goal: Build a Next.js component that uses the useRouter hook to navigate programmatically from the homepage to the profile page when a button is clicked.
📋 What You'll Learn
Create a functional component called HomePage
Import and use the useRouter hook from next/router
Create a button with the text Go to Profile
Add a click handler that uses router.push('/profile') to navigate
💡 Why This Matters
🌍 Real World
Programmatic navigation is common in web apps to move users between pages based on actions like button clicks or form submissions.
💼 Career
Understanding useRouter and programmatic navigation is essential for building interactive Next.js applications and is a common task in frontend development roles.
Progress0 / 4 steps
1
Set up the HomePage component
Create a functional component called HomePage that returns a div with the text Welcome to the homepage.
NextJS
Need a hint?

Use a function that returns JSX with a div containing the welcome text.

2
Import useRouter from next/router
Add an import statement to import useRouter from next/router at the top of the file.
NextJS
Need a hint?

Use import { useRouter } from 'next/router'; at the top.

3
Create router instance and add button
Inside the HomePage component, create a constant called router by calling useRouter(). Then add a button with the text Go to Profile inside the returned div.
NextJS
Need a hint?

Create const router = useRouter(); and add a button inside the div.

4
Add click handler to navigate programmatically
Add an onClick handler to the button that calls router.push('/profile') to navigate to the profile page when clicked.
NextJS
Need a hint?

Add onClick={() => router.push('/profile')} to the button.