Sunday, November 17, 2024
Google search engine
HomeLanguagesNext.js Optional catch all routes

Next.js Optional catch all routes

In this article, we will learn how we can optional catch-all routes in our NextJS 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 NextJs project using the below command:

npx create-next-app gfg

After creating your project folder(i.e. gfg), move to it by using the following command.

cd gfg

Project Structure: It will look like this.

Optional Catch all routes: We can make catch-all routes optional in NextJs using optional catch-all routes.  For this, we have to add three dots inside the double square brackets in the name of the file. For example:-

./pages/[[...file_name]].js

Now let’s create a new dynamic route to optionally catch all the paths. For this, we are going to create a new javascript file inside a new route folder in our pages directory with the name [[…gfg]].js. After that add the below content in that file.

Javascript




// Importing useRouter()
import { useRouter } from 'next/router'
  
function Gfg(){
  // Initializing useRouter()
  const router = useRouter()
  
  return <h1>Path :- {router.asPath} </h1>
}
  
export default Gfg;


Here we are using use router to get the value of the current path and then we are displaying the current Pathname.

Step to Run Application: Run the application using the following command from the root directory of the project.

npm run dev

Output:

How is catch-all routes different from optional catch-all routes: In optional catch-all routes the route without the parameter will also get match ( in the above example ‘/route’ is also matching) but in catch-all routes, the route without the parameter will not match.

Lets change the above optional catch all routes file [[.gfg]].js to catch all routes file […gfg].js with the below content.

Javascript




// Importing useRouter()
import { useRouter } from 'next/router'
  
function Gfg(){
  // Initializing useRouter()
  const router = useRouter()
  
  return <h1>Path :- {router.asPath} </h1>
}
  
export default Gfg;


Now this will not match the path ‘/route’.

Step to Run Application: Run the application using the following command from the root directory of the project.

npm run dev

Output:

Whether you’re preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, neveropen Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we’ve already empowered, and we’re here to do the same for you. Don’t miss out – check it out now!

RELATED ARTICLES

Most Popular

Recent Comments