To learn a new software engineer language or framework could be a difficult task, here is a simple tutorial on how to use URL query parameters in a new file page component in Next.js:
Step 1: Setting up a New Next.js Project
If you don’t already have a Next.js project, you can create one by running the following commands:
npx create-next-app@latest my-next-app
cd my-next-app
npm run dev
This sets up a basic Next.js app and runs the development server at http://localhost:3000.
Step 2: Creating a New Page Component
Next.js provides a file-based routing system. You can create a new page by adding a file inside the pages directory.
Let’s create a new page component at pages/user.js.
Inside the pages folder, create a new file called user.js.
Now, add the following code to the user.js file:
// pages/user.js
import { useRouter } from 'next/router';
const UserPage = () => {
const router = useRouter();
const { name, age } = router.query;
return (
<div>
<h1>User Information</h1>
<p><strong>Name:</strong> {name ? name : 'Unknown'}</p>
<p><strong>Age:</strong> {age ? age : 'Unknown'}</p>
</div>
);
};
export default UserPage;
Step 3: Understanding the Code
useRouter: This is a Next.js hook that gives you access to the router object, which contains the URL information. You can extract the query parameters from router.query.
router.query: Contains the query parameters from the URL. In this example, we extract name and age.
Step 4: Testing URL Query Parameters
Now that you’ve set up the page, let’s pass some query parameters.
Start your development server if it’s not already running:
npm run dev
Go to the browser and visit the following URL:
http://localhost:3000/user?name=John&age=30
You should see the page displaying the user’s name as "John" and age as "30". If you visit the page without query parameters, it will display "Unknown" for both fields:
http://localhost:3000/user
Step 5: Adding Default Values (Optional)
If you want to provide default values for the query parameters, you can modify the component like this:
// pages/user.js
import { useRouter } from 'next/router';
const UserPage = () => {
const router = useRouter();
const { name = 'Guest', age = 'N/A' } = router.query; // Set default values
return (
<div>
<h1>User Information</h1>
<p><strong>Name:</strong> {name}</p>
<p><strong>Age:</strong> {age}</p>
</div>
);
};
export default UserPage;
Conclusion
You’ve now learned how to capture and display URL query parameters in a Next.js page component using the useRouter hook. This is useful for passing data through the URL, like user info, filters, or any dynamic content.