Next.js Linking to dynamic paths
In this article, we will learn, how we can create and link dynamic paths in our Next.js project. NextJS is a React-based framework. It has the power to Develop beautiful Web applications for different platforms like Windows, Linux, and Mac. The linking of dynamic paths helps in rendering your NextJS components conditionally.
Create NextJS Application: You can create a new Next.js project using the below command:
npx create-next-app GFG
Project Structure: It will look like this.
Creating Dynamic Paths: In Next.js, we can create dynamic routes by adding brackets in the name of the page. Here we are going to create one folder named gfg and inside this folder, we will create our file [id].js file as shown below.
Filename: [id].js Now we will display our path using the useRouter() function in this file.
Javascript
import { useRouter } from 'next/router'
const Gfg = () => {
const router = useRouter()
return <h1>Path :- {router.query.id} </h1>
}
export default Gfg;
|
Step to run the application: Now start the application by running the following command.
npm start
Output:
Linking to Dynamic Paths: In Next.js, we can easily link to dynamic paths using the LInk component. Adding the below code in the index.js file.
Filename: index.js
Javascript
import Link from 'next/link'
export default function Home() {
return (
<div>
{ }
<h1>
This is Homepage
</h1>
{ }
<Link href= '/gfg/abc' >
<a>
<button>Go to gfg/abc</button>
</a>
</Link>
<br/>
<Link href= '/gfg/123' >
<a>
<button>Go to gfg/123</button>
</a>
</Link>
<br/>
<Link href= '/gfg/abc123' >
<a>
<button>Go to gfg/abc123</button>
</a>
</Link>
</div>
)
}
|
Step to run the application: Now start the application by running the following command.
npm start
Output:
Last Updated :
10 Oct, 2021
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...