Skip to content
Related Articles

Related Articles

Improve Article
Save Article
Like Article

Next.js Linking to dynamic paths

  • Last Updated : 10 Oct, 2021

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:

Hey geek! The constant emerging technologies in the world of web development always keeps the excitement for this subject through the roof. But before you tackle the big projects, we suggest you start by learning the basics. Kickstart your web development journey by learning JS concepts with our JavaScript Course. Now at it's lowest price ever!


My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!