Open In App

Next.js Linking to dynamic paths

Improve
Improve
Like Article
Like
Save
Share
Report

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




// Importing useRouter()
import { useRouter } from 'next/router'
  
const Gfg = () => {
  
  // Initializing useRouter()
  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 component
import Link from 'next/link'
  
export default function Home() {
  return (
    <div>
      {/* Adding Heading */}
      <h1>
        This is Homepage
      </h1>
      {/* Adding Buttons */}
      <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
Previous
Next
Share your thoughts in the comments
Similar Reads