next js Pages with Dynamic Routes
Step 1: Create a new Next.js project using the following commands:
npx create-next-app my-nextjs-app
cd my-nextjs-app
Step 2: Inside the "pages" directory, create a new file named [id].js
. This file will handle dynamic routes, where "id" can be any variable.
Step 3: Open the [id].js
file and import the necessary modules:
import { useRouter } from 'next/router';
Step 4: Define the React functional component that will use the dynamic route parameter:
function DynamicPage() {
const router = useRouter();
const { id } = router.query;
return (
<div>
<h1>Dynamic Page</h1>
<p>Dynamic ID: {id}</p>
</div>
);
}
export default DynamicPage;
Step 5: Export the component as the default export.
Step 6: To link to the dynamic page, modify the index.js
file in the "pages" directory:
import Link from 'next/link';
function HomePage() {
return (
<div>
<h1>Home Page</h1>
<Link href="/[id]" as="/123">
<a>Go to Dynamic Page with ID 123</a>
</Link>
</div>
);
}
export default HomePage;
Step 7: Run your Next.js application:
npm run dev
Step 8: Open your browser and go to http://localhost:3000
. Click the link to navigate to the dynamic page with the specified ID.
That's it! Now you have a Next.js application with dynamic routes.