SlideShare une entreprise Scribd logo
1  sur  25
Routing in NextJS
Anisha Dahal
What is Routing?
Routing is the process of navigating to different pages on a website….
NextJS Routing
NextJS has FILE SYSTEM BASED ROUTER
Routing Convention is that when a file is added to the pages directory, it is automatically added as a route
NextJS Routing
Options
1. Route with Pages
2. Nested Routes
3. Dynamic Routes
4. Catch-all Routes
5. Navigation from the UI
6. Programmatically
navigate between pages
Routing with Pages
File system based routing feature
How you create your pages determines
the routes!
No need to install Router
No need to configure route with any code
Create files and directories and TaDa!
How does that work?
index.js corresponds to the domain root
Pages are associated with a route based on
their file name
So we got our pages
/ /about
/blog /profile
Routing with pages
Nested Routes
We got a route like this localhost:3000/blog
But, we also need nested routes
localhost:3000/blog/first
localhost:3000/blog/second
How can we get these? -> NextJS’s File Based Router
Nest folders inside pages folder, and
you got your nested routes
How does that work?
index.js here corresponds to the root of folder
name as a route
i.e. /blog
So we got our pages
localhost:3000/blog
localhost:3000/blog/first
localhost:3000/blog/second
Nested Routes
Dynamic Routes
Defining routes by using predefined paths is
not always ideal.
Let’s say, there are 100s of blog posts
Creating a file for each of the post is not
practical.
This is when we go for the dynamic routes!
/product
/product/1
/product/id
Product lists
Product Details Product 1 Details
How does that work?
In this scenario, the product id (1 ,2, 3…)
should be a dynamic value that maps to a
particular file in the product folder
Add Brackets -> [ ] to a page file name to
create a dynamic route
Here, [productId].js
[productId] can be anything
1,2,3, shirt, sweater, laptop,
keyboard…
Dynamic Routes
Nested Dynamic Routes
Lets navigate to the second review of first product
localhost:3000/product/1/review/2
We want review to be nested inside the productId
Whenever we have multiple path segments, nested
folder structure creating nested dynamic routes is the
answer!
/product/1
Product 1
Details
Product 1 Details
/product/1/review/2
How does that work?
Similar to productId, here reviewId is a
dynamic value that maps to a dynamic review
file inside review folder.
review is itself nested inside productId.
Clearly [reviewId] represents a single review
of a single product
Nested Dynamic Routes
Catch All Routes
Another way for handling multiple path
segments.
Let’s say, there are 20 articles and each article
has 20 reviews
20 articles * 20 reviews = 400 files
20 articles *1 [reviewId] = 20 files
1[articleId] * 1[reviewId] = 1 file
Lets say each review can have replies too.
Then we would have to nest another dynamic path
inside review as reply/[replyId]
To make this nesting bit simpler, we can define 1
file to catch all the route segments in the router
And this is when we use Catch All Routes feature
of NextJS.
How does that work?
Catch All Routes catches all the url segments
and maps into the single file([...params].js) in
the project
Define it once and render it for multiple
variations of url!
[...params] will match any url that
contains /articles segment in the
path
Catch All Routes
Where does that work?
A Use Case: To pass filtered params for a page
Example: realestate site
houses/min-budget/max-budget
Catch All Routes
Applicable in: Documentation sites
where we want different path segments for
better organization but the layout for the
document will remain the same
/docs/feature1/concept1/example1
Navigation from the UI
NextJS provides Link Component for client side navigation
To navigate to a URI outside the application, we still need to use
HTML <a> tag.
import Link from "next/link";
<Link href="/about">
<a>About</a>
</Link>
Navigation from the UI
We use String Interpolation for navigating
through Dynamic Links
import Link from "next/link";
<Link href={`/product/${productId}`}>
<a> Product {productId} </a>
</Link>
Note: Push vs Replace
Replace prop in Link component, the current path
replaces the top of the stack
<Link href="/product/3" replace>
<a> Product 3 </a>
</Link>
By default, Navigation using Link
component pushes a path on the top
of a stack (of paths navigated)
Navigation from the UI
sweater /product/sweater
product /product
home /
sweater /product/sweater
home /
So if we go back in browser we navigate to home in the second case
When do we need Replace?
Replace prop in Link component, the current path
replaces the top of the stack
<Link href="/product/3" replace
>
<a> Product 3 </a>
</Link>
Navigation from the UI
sweater /product/sweater
home /
Use Case:
When the user navigates to a invalid route, we can use the
router.replace to prevent the user to navigate back to the
invalid route.
Navigating Programmatically
Link Component covers the most part of client side
navigation
However, there may be need to navigate programmatically
to a route.
For this, we use useRouter hook
How does that work?
router object is accessed inside the function
component and we navigate by pushing a new
path to the router history
We can also replace the path on the top of
stack as
router.replace("/product")
Navigating Programmatically
<button onClick={handleClick}>
Place Order
</button>
//navigating programmatically
const router = useRouter()
const handleClick = () => {
console.log("Placing your order")
router.push("/product")
}
Where does that work?
Navigating Programmatically
Applicable in: Ecommerce Sites
Let’s say, we are placing an order on Amazon.
If form submission is success —> We navigate to the order confirmation page
Shallow Routing
Navigating Programmatically
Shallow routing is when you change your website's URL without re-running data fetching methods again.
Means you have one page component that covers multiple URLs!
Use Case: For adding query strings, and routes
that might explain the content of your pages as they change to user behavior.
router.push("/?counter=10", undefined, { shallow: true })
Base Path
Navigating Programmatically
Default base path is “/”
If we want to deploy our application under a
sub-domain, we can configure our custom
base path
How?
Set path prefix of the application using
“basePath” in “next.config.js” file
Example
module.exports = { basePath: '/docs'}
How it affects routing?
<Link href="/docs/about">
<a>About Page</a>
</Link>
Thanks!

Contenu connexe

Tendances

Next.js vs React | what to choose for frontend development_
Next.js vs React | what to choose for frontend development_Next.js vs React | what to choose for frontend development_
Next.js vs React | what to choose for frontend development_ForceBolt
 
Next.js Introduction
Next.js IntroductionNext.js Introduction
Next.js IntroductionSaray Chak
 
React.js and Redux overview
React.js and Redux overviewReact.js and Redux overview
React.js and Redux overviewAlex Bachuk
 
Introduction to ReactJS
Introduction to ReactJSIntroduction to ReactJS
Introduction to ReactJSKnoldus Inc.
 
TypeScript for Java Developers
TypeScript for Java DevelopersTypeScript for Java Developers
TypeScript for Java DevelopersYakov Fain
 
An Introduction to CSS Preprocessors (SASS & LESS)
An Introduction to CSS Preprocessors (SASS & LESS)An Introduction to CSS Preprocessors (SASS & LESS)
An Introduction to CSS Preprocessors (SASS & LESS)Folio3 Software
 
Getting started with Next.js - IM Tech Meetup - Oct 2022.pptx
Getting started with Next.js - IM Tech Meetup - Oct 2022.pptxGetting started with Next.js - IM Tech Meetup - Oct 2022.pptx
Getting started with Next.js - IM Tech Meetup - Oct 2022.pptxIlesh Mistry
 
React state managmenet with Redux
React state managmenet with ReduxReact state managmenet with Redux
React state managmenet with ReduxVedran Blaženka
 
AngularJS for Beginners
AngularJS for BeginnersAngularJS for Beginners
AngularJS for BeginnersEdureka!
 

Tendances (20)

Next.js vs React | what to choose for frontend development_
Next.js vs React | what to choose for frontend development_Next.js vs React | what to choose for frontend development_
Next.js vs React | what to choose for frontend development_
 
An Introduction to Redux
An Introduction to ReduxAn Introduction to Redux
An Introduction to Redux
 
Next.js Introduction
Next.js IntroductionNext.js Introduction
Next.js Introduction
 
React.js and Redux overview
React.js and Redux overviewReact.js and Redux overview
React.js and Redux overview
 
Basics of JavaScript
Basics of JavaScriptBasics of JavaScript
Basics of JavaScript
 
TypeScript - An Introduction
TypeScript - An IntroductionTypeScript - An Introduction
TypeScript - An Introduction
 
Introduction to ReactJS
Introduction to ReactJSIntroduction to ReactJS
Introduction to ReactJS
 
TypeScript for Java Developers
TypeScript for Java DevelopersTypeScript for Java Developers
TypeScript for Java Developers
 
Universal React apps in Next.js
Universal React apps in Next.jsUniversal React apps in Next.js
Universal React apps in Next.js
 
An Introduction to CSS Preprocessors (SASS & LESS)
An Introduction to CSS Preprocessors (SASS & LESS)An Introduction to CSS Preprocessors (SASS & LESS)
An Introduction to CSS Preprocessors (SASS & LESS)
 
Server side rendering review
Server side rendering reviewServer side rendering review
Server side rendering review
 
Getting started with Next.js - IM Tech Meetup - Oct 2022.pptx
Getting started with Next.js - IM Tech Meetup - Oct 2022.pptxGetting started with Next.js - IM Tech Meetup - Oct 2022.pptx
Getting started with Next.js - IM Tech Meetup - Oct 2022.pptx
 
React state managmenet with Redux
React state managmenet with ReduxReact state managmenet with Redux
React state managmenet with Redux
 
Workshop 21: React Router
Workshop 21: React RouterWorkshop 21: React Router
Workshop 21: React Router
 
Introduction to Redux
Introduction to ReduxIntroduction to Redux
Introduction to Redux
 
AngularJS for Beginners
AngularJS for BeginnersAngularJS for Beginners
AngularJS for Beginners
 
React JS
React JSReact JS
React JS
 
Express js
Express jsExpress js
Express js
 
Redux workshop
Redux workshopRedux workshop
Redux workshop
 
Windows Communication Foundation (WCF)
Windows Communication Foundation (WCF)Windows Communication Foundation (WCF)
Windows Communication Foundation (WCF)
 

Similaire à Routing in NEXTJS.pdf

AngularJS Fundamentals + WebAPI
AngularJS Fundamentals + WebAPIAngularJS Fundamentals + WebAPI
AngularJS Fundamentals + WebAPIEric Wise
 
Getting started with hot towel spa
Getting started with hot towel spaGetting started with hot towel spa
Getting started with hot towel spaparth17290
 
Progressive EPiServer Development
Progressive EPiServer DevelopmentProgressive EPiServer Development
Progressive EPiServer Developmentjoelabrahamsson
 
8 things you didn't know about the Angular Router, you won't believe #6!
8 things you didn't know about the Angular Router, you won't believe #6!8 things you didn't know about the Angular Router, you won't believe #6!
8 things you didn't know about the Angular Router, you won't believe #6!Laurent Duveau
 
IBIS - Intelligent Band Information System
IBIS - Intelligent Band Information SystemIBIS - Intelligent Band Information System
IBIS - Intelligent Band Information SystemMicron
 
331592291-HTML-and-Cascading style sheet
331592291-HTML-and-Cascading style sheet331592291-HTML-and-Cascading style sheet
331592291-HTML-and-Cascading style sheetstephen972973
 
ngNewRouter
ngNewRouterngNewRouter
ngNewRouterphidong
 
AngularJS training - Day 1 - Basics: Why, What and basic features of AngularJS
AngularJS training - Day 1 - Basics: Why, What and basic features of AngularJSAngularJS training - Day 1 - Basics: Why, What and basic features of AngularJS
AngularJS training - Day 1 - Basics: Why, What and basic features of AngularJSmurtazahaveliwala
 
Routing & Navigating Pages in Angular 2
Routing & Navigating Pages in Angular 2Routing & Navigating Pages in Angular 2
Routing & Navigating Pages in Angular 2Knoldus Inc.
 
Code igniter - A brief introduction
Code igniter - A brief introductionCode igniter - A brief introduction
Code igniter - A brief introductionCommit University
 
End to end testing Single Page Apps & APIs with Cucumber.js and Puppeteer (Em...
End to end testing Single Page Apps & APIs with Cucumber.js and Puppeteer (Em...End to end testing Single Page Apps & APIs with Cucumber.js and Puppeteer (Em...
End to end testing Single Page Apps & APIs with Cucumber.js and Puppeteer (Em...Paul Jensen
 
AngularJS 101 - Everything you need to know to get started
AngularJS 101 - Everything you need to know to get startedAngularJS 101 - Everything you need to know to get started
AngularJS 101 - Everything you need to know to get startedStéphane Bégaudeau
 
ASP.NET 04 - Additional Web Server Controls
ASP.NET 04 - Additional Web Server ControlsASP.NET 04 - Additional Web Server Controls
ASP.NET 04 - Additional Web Server ControlsRandy Connolly
 
Buiding Next Generation Websites Session 8 by Muhammad Ehtisham Siddiqui
Buiding Next Generation Websites Session 8 by Muhammad Ehtisham SiddiquiBuiding Next Generation Websites Session 8 by Muhammad Ehtisham Siddiqui
Buiding Next Generation Websites Session 8 by Muhammad Ehtisham SiddiquiMuhammad Ehtisham Siddiqui
 
Lecture14 abap on line
Lecture14 abap on lineLecture14 abap on line
Lecture14 abap on lineMilind Patil
 

Similaire à Routing in NEXTJS.pdf (20)

Chapter5.pptx
Chapter5.pptxChapter5.pptx
Chapter5.pptx
 
Express node js
Express node jsExpress node js
Express node js
 
Angular2 routing
Angular2 routingAngular2 routing
Angular2 routing
 
AngularJS Fundamentals + WebAPI
AngularJS Fundamentals + WebAPIAngularJS Fundamentals + WebAPI
AngularJS Fundamentals + WebAPI
 
Getting started with hot towel spa
Getting started with hot towel spaGetting started with hot towel spa
Getting started with hot towel spa
 
Progressive EPiServer Development
Progressive EPiServer DevelopmentProgressive EPiServer Development
Progressive EPiServer Development
 
8 things you didn't know about the Angular Router, you won't believe #6!
8 things you didn't know about the Angular Router, you won't believe #6!8 things you didn't know about the Angular Router, you won't believe #6!
8 things you didn't know about the Angular Router, you won't believe #6!
 
IBIS - Intelligent Band Information System
IBIS - Intelligent Band Information SystemIBIS - Intelligent Band Information System
IBIS - Intelligent Band Information System
 
331592291-HTML-and-Cascading style sheet
331592291-HTML-and-Cascading style sheet331592291-HTML-and-Cascading style sheet
331592291-HTML-and-Cascading style sheet
 
ngNewRouter
ngNewRouterngNewRouter
ngNewRouter
 
AngularJS training - Day 1 - Basics: Why, What and basic features of AngularJS
AngularJS training - Day 1 - Basics: Why, What and basic features of AngularJSAngularJS training - Day 1 - Basics: Why, What and basic features of AngularJS
AngularJS training - Day 1 - Basics: Why, What and basic features of AngularJS
 
Routing & Navigating Pages in Angular 2
Routing & Navigating Pages in Angular 2Routing & Navigating Pages in Angular 2
Routing & Navigating Pages in Angular 2
 
Code igniter - A brief introduction
Code igniter - A brief introductionCode igniter - A brief introduction
Code igniter - A brief introduction
 
End to end testing Single Page Apps & APIs with Cucumber.js and Puppeteer (Em...
End to end testing Single Page Apps & APIs with Cucumber.js and Puppeteer (Em...End to end testing Single Page Apps & APIs with Cucumber.js and Puppeteer (Em...
End to end testing Single Page Apps & APIs with Cucumber.js and Puppeteer (Em...
 
Switch to Svelte | GDSC NIT Silchar | Speaker Session | SvelteKit
Switch to Svelte | GDSC NIT Silchar | Speaker Session | SvelteKitSwitch to Svelte | GDSC NIT Silchar | Speaker Session | SvelteKit
Switch to Svelte | GDSC NIT Silchar | Speaker Session | SvelteKit
 
AngularJS 101 - Everything you need to know to get started
AngularJS 101 - Everything you need to know to get startedAngularJS 101 - Everything you need to know to get started
AngularJS 101 - Everything you need to know to get started
 
ASP.NET 04 - Additional Web Server Controls
ASP.NET 04 - Additional Web Server ControlsASP.NET 04 - Additional Web Server Controls
ASP.NET 04 - Additional Web Server Controls
 
Nodejs.meetup
Nodejs.meetupNodejs.meetup
Nodejs.meetup
 
Buiding Next Generation Websites Session 8 by Muhammad Ehtisham Siddiqui
Buiding Next Generation Websites Session 8 by Muhammad Ehtisham SiddiquiBuiding Next Generation Websites Session 8 by Muhammad Ehtisham Siddiqui
Buiding Next Generation Websites Session 8 by Muhammad Ehtisham Siddiqui
 
Lecture14 abap on line
Lecture14 abap on lineLecture14 abap on line
Lecture14 abap on line
 

Dernier

microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introductionMaksud Ahmed
 
Activity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfActivity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfciinovamais
 
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Krashi Coaching
 
Separation of Lanthanides/ Lanthanides and Actinides
Separation of Lanthanides/ Lanthanides and ActinidesSeparation of Lanthanides/ Lanthanides and Actinides
Separation of Lanthanides/ Lanthanides and ActinidesFatimaKhan178732
 
Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104misteraugie
 
Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17Celine George
 
Hybridoma Technology ( Production , Purification , and Application )
Hybridoma Technology  ( Production , Purification , and Application  ) Hybridoma Technology  ( Production , Purification , and Application  )
Hybridoma Technology ( Production , Purification , and Application ) Sakshi Ghasle
 
Industrial Policy - 1948, 1956, 1973, 1977, 1980, 1991
Industrial Policy - 1948, 1956, 1973, 1977, 1980, 1991Industrial Policy - 1948, 1956, 1973, 1977, 1980, 1991
Industrial Policy - 1948, 1956, 1973, 1977, 1980, 1991RKavithamani
 
Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)eniolaolutunde
 
1029-Danh muc Sach Giao Khoa khoi 6.pdf
1029-Danh muc Sach Giao Khoa khoi  6.pdf1029-Danh muc Sach Giao Khoa khoi  6.pdf
1029-Danh muc Sach Giao Khoa khoi 6.pdfQucHHunhnh
 
Privatization and Disinvestment - Meaning, Objectives, Advantages and Disadva...
Privatization and Disinvestment - Meaning, Objectives, Advantages and Disadva...Privatization and Disinvestment - Meaning, Objectives, Advantages and Disadva...
Privatization and Disinvestment - Meaning, Objectives, Advantages and Disadva...RKavithamani
 
Beyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactBeyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactPECB
 
Sanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfSanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfsanyamsingh5019
 
Introduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxIntroduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxpboyjonauth
 
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Sapana Sha
 
Paris 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityParis 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityGeoBlogs
 
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...EduSkills OECD
 
Arihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdfArihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdfchloefrazer622
 

Dernier (20)

microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introduction
 
Activity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfActivity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdf
 
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
 
Separation of Lanthanides/ Lanthanides and Actinides
Separation of Lanthanides/ Lanthanides and ActinidesSeparation of Lanthanides/ Lanthanides and Actinides
Separation of Lanthanides/ Lanthanides and Actinides
 
Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104
 
Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17
 
Hybridoma Technology ( Production , Purification , and Application )
Hybridoma Technology  ( Production , Purification , and Application  ) Hybridoma Technology  ( Production , Purification , and Application  )
Hybridoma Technology ( Production , Purification , and Application )
 
Industrial Policy - 1948, 1956, 1973, 1977, 1980, 1991
Industrial Policy - 1948, 1956, 1973, 1977, 1980, 1991Industrial Policy - 1948, 1956, 1973, 1977, 1980, 1991
Industrial Policy - 1948, 1956, 1973, 1977, 1980, 1991
 
Código Creativo y Arte de Software | Unidad 1
Código Creativo y Arte de Software | Unidad 1Código Creativo y Arte de Software | Unidad 1
Código Creativo y Arte de Software | Unidad 1
 
Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)
 
1029-Danh muc Sach Giao Khoa khoi 6.pdf
1029-Danh muc Sach Giao Khoa khoi  6.pdf1029-Danh muc Sach Giao Khoa khoi  6.pdf
1029-Danh muc Sach Giao Khoa khoi 6.pdf
 
Privatization and Disinvestment - Meaning, Objectives, Advantages and Disadva...
Privatization and Disinvestment - Meaning, Objectives, Advantages and Disadva...Privatization and Disinvestment - Meaning, Objectives, Advantages and Disadva...
Privatization and Disinvestment - Meaning, Objectives, Advantages and Disadva...
 
Staff of Color (SOC) Retention Efforts DDSD
Staff of Color (SOC) Retention Efforts DDSDStaff of Color (SOC) Retention Efforts DDSD
Staff of Color (SOC) Retention Efforts DDSD
 
Beyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactBeyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global Impact
 
Sanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfSanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdf
 
Introduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxIntroduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptx
 
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
 
Paris 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityParis 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activity
 
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
 
Arihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdfArihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdf
 

Routing in NEXTJS.pdf

  • 2. What is Routing? Routing is the process of navigating to different pages on a website….
  • 3. NextJS Routing NextJS has FILE SYSTEM BASED ROUTER Routing Convention is that when a file is added to the pages directory, it is automatically added as a route
  • 4. NextJS Routing Options 1. Route with Pages 2. Nested Routes 3. Dynamic Routes 4. Catch-all Routes 5. Navigation from the UI 6. Programmatically navigate between pages
  • 5. Routing with Pages File system based routing feature How you create your pages determines the routes! No need to install Router No need to configure route with any code Create files and directories and TaDa!
  • 6. How does that work? index.js corresponds to the domain root Pages are associated with a route based on their file name So we got our pages / /about /blog /profile Routing with pages
  • 7. Nested Routes We got a route like this localhost:3000/blog But, we also need nested routes localhost:3000/blog/first localhost:3000/blog/second How can we get these? -> NextJS’s File Based Router Nest folders inside pages folder, and you got your nested routes
  • 8. How does that work? index.js here corresponds to the root of folder name as a route i.e. /blog So we got our pages localhost:3000/blog localhost:3000/blog/first localhost:3000/blog/second Nested Routes
  • 9. Dynamic Routes Defining routes by using predefined paths is not always ideal. Let’s say, there are 100s of blog posts Creating a file for each of the post is not practical. This is when we go for the dynamic routes! /product /product/1 /product/id Product lists Product Details Product 1 Details
  • 10. How does that work? In this scenario, the product id (1 ,2, 3…) should be a dynamic value that maps to a particular file in the product folder Add Brackets -> [ ] to a page file name to create a dynamic route Here, [productId].js [productId] can be anything 1,2,3, shirt, sweater, laptop, keyboard… Dynamic Routes
  • 11. Nested Dynamic Routes Lets navigate to the second review of first product localhost:3000/product/1/review/2 We want review to be nested inside the productId Whenever we have multiple path segments, nested folder structure creating nested dynamic routes is the answer! /product/1 Product 1 Details Product 1 Details /product/1/review/2
  • 12. How does that work? Similar to productId, here reviewId is a dynamic value that maps to a dynamic review file inside review folder. review is itself nested inside productId. Clearly [reviewId] represents a single review of a single product Nested Dynamic Routes
  • 13. Catch All Routes Another way for handling multiple path segments. Let’s say, there are 20 articles and each article has 20 reviews 20 articles * 20 reviews = 400 files 20 articles *1 [reviewId] = 20 files 1[articleId] * 1[reviewId] = 1 file Lets say each review can have replies too. Then we would have to nest another dynamic path inside review as reply/[replyId] To make this nesting bit simpler, we can define 1 file to catch all the route segments in the router And this is when we use Catch All Routes feature of NextJS.
  • 14. How does that work? Catch All Routes catches all the url segments and maps into the single file([...params].js) in the project Define it once and render it for multiple variations of url! [...params] will match any url that contains /articles segment in the path Catch All Routes
  • 15. Where does that work? A Use Case: To pass filtered params for a page Example: realestate site houses/min-budget/max-budget Catch All Routes Applicable in: Documentation sites where we want different path segments for better organization but the layout for the document will remain the same /docs/feature1/concept1/example1
  • 16. Navigation from the UI NextJS provides Link Component for client side navigation To navigate to a URI outside the application, we still need to use HTML <a> tag. import Link from "next/link"; <Link href="/about"> <a>About</a> </Link>
  • 17. Navigation from the UI We use String Interpolation for navigating through Dynamic Links import Link from "next/link"; <Link href={`/product/${productId}`}> <a> Product {productId} </a> </Link>
  • 18. Note: Push vs Replace Replace prop in Link component, the current path replaces the top of the stack <Link href="/product/3" replace> <a> Product 3 </a> </Link> By default, Navigation using Link component pushes a path on the top of a stack (of paths navigated) Navigation from the UI sweater /product/sweater product /product home / sweater /product/sweater home / So if we go back in browser we navigate to home in the second case
  • 19. When do we need Replace? Replace prop in Link component, the current path replaces the top of the stack <Link href="/product/3" replace > <a> Product 3 </a> </Link> Navigation from the UI sweater /product/sweater home / Use Case: When the user navigates to a invalid route, we can use the router.replace to prevent the user to navigate back to the invalid route.
  • 20. Navigating Programmatically Link Component covers the most part of client side navigation However, there may be need to navigate programmatically to a route. For this, we use useRouter hook
  • 21. How does that work? router object is accessed inside the function component and we navigate by pushing a new path to the router history We can also replace the path on the top of stack as router.replace("/product") Navigating Programmatically <button onClick={handleClick}> Place Order </button> //navigating programmatically const router = useRouter() const handleClick = () => { console.log("Placing your order") router.push("/product") }
  • 22. Where does that work? Navigating Programmatically Applicable in: Ecommerce Sites Let’s say, we are placing an order on Amazon. If form submission is success —> We navigate to the order confirmation page
  • 23. Shallow Routing Navigating Programmatically Shallow routing is when you change your website's URL without re-running data fetching methods again. Means you have one page component that covers multiple URLs! Use Case: For adding query strings, and routes that might explain the content of your pages as they change to user behavior. router.push("/?counter=10", undefined, { shallow: true })
  • 24. Base Path Navigating Programmatically Default base path is “/” If we want to deploy our application under a sub-domain, we can configure our custom base path How? Set path prefix of the application using “basePath” in “next.config.js” file Example module.exports = { basePath: '/docs'} How it affects routing? <Link href="/docs/about"> <a>About Page</a> </Link>