- Blog Categories
- Software Development
- Data Science
- AI/ML
- Marketing
- General
- MBA
- Management
- Legal
- Software Development Projects and Ideas
- 12 Computer Science Project Ideas
- 28 Beginner Software Projects
- Top 10 Engineering Project Ideas
- Top 10 Easy Final Year Projects
- Top 10 Mini Projects for Engineers
- 25 Best Django Project Ideas
- Top 20 MERN Stack Project Ideas
- Top 12 Real Time Projects
- Top 6 Major CSE Projects
- 12 Robotics Projects for All Levels
- Java Programming Concepts
- Abstract Class in Java and Methods
- Constructor Overloading in Java
- StringBuffer vs StringBuilder
- Java Identifiers: Syntax & Examples
- Types of Variables in Java Explained
- Composition in Java: Examples
- Append in Java: Implementation
- Loose Coupling vs Tight Coupling
- Integrity Constraints in DBMS
- Different Types of Operators Explained
- Career and Interview Preparation in IT
- Top 14 IT Courses for Jobs
- Top 20 Highest Paying Languages
- 23 Top CS Interview Q&A
- Best IT Jobs without Coding
- Software Engineer Salary in India
- 44 Agile Methodology Interview Q&A
- 10 Software Engineering Challenges
- Top 15 Tech's Daily Life Impact
- 10 Best Backends for React
- Cloud Computing Reference Models
- Web Development and Security
- Find Installed NPM Version
- Install Specific NPM Package Version
- Make API Calls in Angular
- Install Bootstrap in Angular
- Use Axios in React: Guide
- StrictMode in React: Usage
- 75 Cyber Security Research Topics
- Top 7 Languages for Ethical Hacking
- Top 20 Docker Commands
- Advantages of OOP
- Data Science Projects and Applications
- 42 Python Project Ideas for Beginners
- 13 Data Science Project Ideas
- 13 Data Structure Project Ideas
- 12 Real-World Python Applications
- Python Banking Project
- Data Science Course Eligibility
- Association Rule Mining Overview
- Cluster Analysis in Data Mining
- Classification in Data Mining
- KDD Process in Data Mining
- Data Structures and Algorithms
- Binary Tree Types Explained
- Binary Search Algorithm
- Sorting in Data Structure
- Binary Tree in Data Structure
- Binary Tree vs Binary Search Tree
- Recursion in Data Structure
- Data Structure Search Methods: Explained
- Binary Tree Interview Q&A
- Linear vs Binary Search
- Priority Queue Overview
- Python Programming and Tools
- Top 30 Python Pattern Programs
- List vs Tuple
- Python Free Online Course
- Method Overriding in Python
- Top 21 Python Developer Skills
- Reverse a Number in Python
- Switch Case Functions in Python
- Info Retrieval System Overview
- Reverse a Number in Python
- Real-World Python Applications
- Data Science Careers and Comparisons
- Data Analyst Salary in India
- Data Scientist Salary in India
- Free Excel Certification Course
- Actuary Salary in India
- Data Analyst Interview Guide
- Pandas Interview Guide
- Tableau Filters Explained
- Data Mining Techniques Overview
- Data Analytics Lifecycle Phases
- Data Science Vs Analytics Comparison
- Artificial Intelligence and Machine Learning Projects
- Exciting IoT Project Ideas
- 16 Exciting AI Project Ideas
- 45+ Interesting ML Project Ideas
- Exciting Deep Learning Projects
- 12 Intriguing Linear Regression Projects
- 13 Neural Network Projects
- 5 Exciting Image Processing Projects
- Top 8 Thrilling AWS Projects
- 12 Engaging AI Projects in Python
- NLP Projects for Beginners
- Concepts and Algorithms in AIML
- Basic CNN Architecture Explained
- 6 Types of Regression Models
- Data Preprocessing Steps
- Bagging vs Boosting in ML
- Multinomial Naive Bayes Overview
- Bayesian Network Example
- Bayes Theorem Guide
- Top 10 Dimensionality Reduction Techniques
- Neural Network Step-by-Step Guide
- Technical Guides and Comparisons
- Make a Chatbot in Python
- Compute Square Roots in Python
- Permutation vs Combination
- Image Segmentation Techniques
- Generative AI vs Traditional AI
- AI vs Human Intelligence
- Random Forest vs Decision Tree
- Neural Network Overview
- Perceptron Learning Algorithm
- Selection Sort Algorithm
- Career and Practical Applications in AIML
- AI Salary in India Overview
- Biological Neural Network Basics
- Top 10 AI Challenges
- Production System in AI
- Top 8 Raspberry Pi Alternatives
- Top 8 Open Source Projects
- 14 Raspberry Pi Project Ideas
- 15 MATLAB Project Ideas
- Top 10 Python NLP Libraries
- Naive Bayes Explained
- Digital Marketing Projects and Strategies
- 10 Best Digital Marketing Projects
- 17 Fun Social Media Projects
- Top 6 SEO Project Ideas
- Digital Marketing Case Studies
- Coca-Cola Marketing Strategy
- Nestle Marketing Strategy Analysis
- Zomato Marketing Strategy
- Monetize Instagram Guide
- Become a Successful Instagram Influencer
- 8 Best Lead Generation Techniques
- Digital Marketing Careers and Salaries
- Digital Marketing Salary in India
- Top 10 Highest Paying Marketing Jobs
- Highest Paying Digital Marketing Jobs
- SEO Salary in India
- Content Writer Salary Guide
- Digital Marketing Executive Roles
- Career in Digital Marketing Guide
- Future of Digital Marketing
- MBA in Digital Marketing Overview
- Digital Marketing Techniques and Channels
- 9 Types of Digital Marketing Channels
- Top 10 Benefits of Marketing Branding
- 100 Best YouTube Channel Ideas
- YouTube Earnings in India
- 7 Reasons to Study Digital Marketing
- Top 10 Digital Marketing Objectives
- 10 Best Digital Marketing Blogs
- Top 5 Industries Using Digital Marketing
- Growth of Digital Marketing in India
- Top Career Options in Marketing
- Interview Preparation and Skills
- 73 Google Analytics Interview Q&A
- 56 Social Media Marketing Q&A
- 78 Google AdWords Interview Q&A
- Top 133 SEO Interview Q&A
- 27+ Digital Marketing Q&A
- Digital Marketing Free Course
- Top 9 Skills for PPC Analysts
- Movies with Successful Social Media Campaigns
- Marketing Communication Steps
- Top 10 Reasons to Be an Affiliate Marketer
- Career Options and Paths
- Top 25 Highest Paying Jobs India
- Top 25 Highest Paying Jobs World
- Top 10 Highest Paid Commerce Job
- Career Options After 12th Arts
- Top 7 Commerce Courses Without Maths
- Top 7 Career Options After PCB
- Best Career Options for Commerce
- Career Options After 12th CS
- Top 10 Career Options After 10th
- 8 Best Career Options After BA
- Projects and Academic Pursuits
- 17 Exciting Final Year Projects
- Top 12 Commerce Project Topics
- Top 13 BCA Project Ideas
- Career Options After 12th Science
- Top 15 CS Jobs in India
- 12 Best Career Options After M.Com
- 9 Best Career Options After B.Sc
- 7 Best Career Options After BCA
- 22 Best Career Options After MCA
- 16 Top Career Options After CE
- Courses and Certifications
- 10 Best Job-Oriented Courses
- Best Online Computer Courses
- Top 15 Trending Online Courses
- Top 19 High Salary Certificate Courses
- 21 Best Programming Courses for Jobs
- What is SGPA? Convert to CGPA
- GPA to Percentage Calculator
- Highest Salary Engineering Stream
- 15 Top Career Options After Engineering
- 6 Top Career Options After BBA
- Job Market and Interview Preparation
- Why Should You Be Hired: 5 Answers
- Top 10 Future Career Options
- Top 15 Highest Paid IT Jobs India
- 5 Common Guesstimate Interview Q&A
- Average CEO Salary: Top Paid CEOs
- Career Options in Political Science
- Top 15 Highest Paying Non-IT Jobs
- Cover Letter Examples for Jobs
- Top 5 Highest Paying Freelance Jobs
- Top 10 Highest Paying Companies India
- Career Options and Paths After MBA
- 20 Best Careers After B.Com
- Career Options After MBA Marketing
- Top 14 Careers After MBA In HR
- Top 10 Highest Paying HR Jobs India
- How to Become an Investment Banker
- Career Options After MBA - High Paying
- Scope of MBA in Operations Management
- Best MBA for Working Professionals India
- MBA After BA - Is It Right For You?
- Best Online MBA Courses India
- MBA Project Ideas and Topics
- 11 Exciting MBA HR Project Ideas
- Top 15 MBA Project Ideas
- 18 Exciting MBA Marketing Projects
- MBA Project Ideas: Consumer Behavior
- What is Brand Management?
- What is Holistic Marketing?
- What is Green Marketing?
- Intro to Organizational Behavior Model
- Tech Skills Every MBA Should Learn
- Most Demanding Short Term Courses MBA
- MBA Salary, Resume, and Skills
- MBA Salary in India
- HR Salary in India
- Investment Banker Salary India
- MBA Resume Samples
- Sample SOP for MBA
- Sample SOP for Internship
- 7 Ways MBA Helps Your Career
- Must-have Skills in Sales Career
- 8 Skills MBA Helps You Improve
- Top 20+ SAP FICO Interview Q&A
- MBA Specializations and Comparative Guides
- Why MBA After B.Tech? 5 Reasons
- How to Answer 'Why MBA After Engineering?'
- Why MBA in Finance
- MBA After BSc: 10 Reasons
- Which MBA Specialization to choose?
- Top 10 MBA Specializations
- MBA vs Masters: Which to Choose?
- Benefits of MBA After CA
- 5 Steps to Management Consultant
- 37 Must-Read HR Interview Q&A
- Fundamentals and Theories of Management
- What is Management? Objectives & Functions
- Nature and Scope of Management
- Decision Making in Management
- Management Process: Definition & Functions
- Importance of Management
- What are Motivation Theories?
- Tools of Financial Statement Analysis
- Negotiation Skills: Definition & Benefits
- Career Development in HRM
- Top 20 Must-Have HRM Policies
- Project and Supply Chain Management
- Top 20 Project Management Case Studies
- 10 Innovative Supply Chain Projects
- Latest Management Project Topics
- 10 Project Management Project Ideas
- 6 Types of Supply Chain Models
- Top 10 Advantages of SCM
- Top 10 Supply Chain Books
- What is Project Description?
- Top 10 Project Management Companies
- Best Project Management Courses Online
- Salaries and Career Paths in Management
- Project Manager Salary in India
- Average Product Manager Salary India
- Supply Chain Management Salary India
- Salary After BBA in India
- PGDM Salary in India
- Top 7 Career Options in Management
- CSPO Certification Cost
- Why Choose Product Management?
- Product Management in Pharma
- Product Design in Operations Management
- Industry-Specific Management and Case Studies
- Amazon Business Case Study
- Service Delivery Manager Job
- Product Management Examples
- Product Management in Automobiles
- Product Management in Banking
- Sample SOP for Business Management
- Video Game Design Components
- Top 5 Business Courses India
- Free Management Online Course
- SCM Interview Q&A
- Fundamentals and Types of Law
- Acceptance in Contract Law
- Offer in Contract Law
- 9 Types of Evidence
- Types of Law in India
- Introduction to Contract Law
- Negotiable Instrument Act
- Corporate Tax Basics
- Intellectual Property Law
- Workmen Compensation Explained
- Lawyer vs Advocate Difference
- Law Education and Courses
- LLM Subjects & Syllabus
- Corporate Law Subjects
- LLM Course Duration
- Top 10 Online LLM Courses
- Online LLM Degree
- Step-by-Step Guide to Studying Law
- Top 5 Law Books to Read
- Why Legal Studies?
- Pursuing a Career in Law
- How to Become Lawyer in India
- Career Options and Salaries in Law
- Career Options in Law India
- Corporate Lawyer Salary India
- How To Become a Corporate Lawyer
- Career in Law: Starting, Salary
- Career Opportunities: Corporate Law
- Business Lawyer: Role & Salary Info
- Average Lawyer Salary India
- Top Career Options for Lawyers
- Types of Lawyers in India
- Steps to Become SC Lawyer in India
- Tutorials
- Software Tutorials
- C Tutorials
- Recursion in C: Fibonacci Series
- Checking String Palindromes in C
- Prime Number Program in C
- Implementing Square Root in C
- Matrix Multiplication in C
- Understanding Double Data Type
- Factorial of a Number in C
- Structure of a C Program
- Building a Calculator Program in C
- Compiling C Programs on Linux
- Java Tutorials
- Handling String Input in Java
- Determining Even and Odd Numbers
- Prime Number Checker
- Sorting a String
- User-Defined Exceptions
- Understanding the Thread Life Cycle
- Swapping Two Numbers
- Using Final Classes
- Area of a Triangle
- Skills
- Explore Skills
- Management Skills
- Software Engineering
- JavaScript
- Data Structure
- React.js
- Core Java
- Node.js
- Blockchain
- SQL
- Full stack development
- Devops
- NFT
- BigData
- Cyber Security
- Cloud Computing
- Database Design with MySQL
- Cryptocurrency
- Python
- Digital Marketings
- Advertising
- Influencer Marketing
- Performance Marketing
- Search Engine Marketing
- Email Marketing
- Content Marketing
- Social Media Marketing
- Display Advertising
- Marketing Analytics
- Web Analytics
- Affiliate Marketing
- MBA
- MBA in Finance
- MBA in HR
- MBA in Marketing
- MBA in Business Analytics
- MBA in Operations Management
- MBA in International Business
- MBA in Information Technology
- MBA in Healthcare Management
- MBA In General Management
- MBA in Agriculture
- MBA in Supply Chain Management
- MBA in Entrepreneurship
- MBA in Project Management
- Management Program
- Consumer Behaviour
- Supply Chain Management
- Financial Analytics
- Introduction to Fintech
- Introduction to HR Analytics
- Fundamentals of Communication
- Art of Effective Communication
- Introduction to Research Methodology
- Mastering Sales Technique
- Business Communication
- Fundamentals of Journalism
- Economics Masterclass
- Free Courses
Routing in ReactJS for Beginners [With Examples]
Updated on 31 October, 2024
41.57K+ views
• 17 min read
Table of Contents
- Basic Routing
- How Routing Works / Routing Mechanism
- Installation and the Steps for React Router
- Source Code and Snippets
- React Router: Challenges and Debugging
- How to Use React Router in Typescript
- React Router Examples
- Different Types of Routers in React Router
- Components in React Router and their Explanation
- What is the Difference Between React Router and React Router DOM?
- Conclusion
Routing in reactJS is the mechanism by which we navigate through a website or web-application. Routing can be server-side routing or client-side routing. However, React Router is a part of client-side routing. Before proceeding further it is highly recommended you go over the official React.js certification course to familiarize yourself with the fundamentals of React.
React Routing without any knowledge of it can be manually implemented using useState and JSX for conditioning. But being inefficient for large-scale applications like e-commerce, it still can act as a boilerplate for understanding routing and act as a base for React JS router for example.
const[page, setpage] = useState("products")
const routeTo = (newpage) =>{
setpage(newpage)
}
<button onClick={()= routeTo("cart")}> Cart />
{page === "cart" && (
<Cart cart={cart} setcart={setcart}/>)}
Server-side routing results in every request being a full page refresh loading unnecessary and repeated data every time causing a bad UX and delay in loading.
With client-side routing, it could be the rendering of a new component where routing is handled internally by JavaScript. The component is rendered only without the server being reloaded.
React Router helps us to navigate the components and build a single-page application without page-refresh when the user navigates making it an effective UX experience.
Web-Development is the heart of routing. Routing takes place efficiently in websites and so to understand it, one must know a basic boilerplate of Web Development complete course followed by a React.js certification course to rocket-start React-Routing!
Basic Routing
React Router API
Browser Router or React Router API is a most popular library for routing in react to navigate among different components in a React Application keeping the UI in alignment with URL.
According to react-router official docs, “ React Router is a fully-featured client and server-side routing library for React, a JavaScript library for building user interfaces.”
Various Packages in React Router Library
There are 3 different packages for React Routing.
- react-router: It is the heart of react-router and provides core functionalities for routing in web applications and all the packages for react-router- dom and react-router-native
- react-router-native: It is used for routing in mobile applications
- react-router-dom: It is used to implement dynamic routing in web applications.
How Routing Works / Routing Mechanism
We know routing is user-side navigation to different pages or different pages on a website. Every rendering mechanism has its own routing way to navigate but dealing with React Router here that comes under Client Side Routing but eventually under Client Side Rendering has a dynamic mechanism to look upon.
Client Side rendering orders the server to deal with data only whereas the rest of all rendering and routing is handled by the client itself.
Traditional routing has always requested the server to provide different index.html of different pages, but Client Side Rendering will only return one index.html file for Client Side Routing.
This will give you a smooth Single Page Application Routing experience with forward and backward route ability using history API keeping the URL updated as well.
Installation and the Steps for React Router
Prerequisite for react-router dom install:
- You must have a react app created using create-react-app
- The react app must be running with dummy code to proceed with creating react app router
React Router will help us make a dynamic navbar with different links to route on, resembling a blog application where every link routes us to a different new page.
Step 1: Run the following commands in terminal
npm install react-router-dom@6
or
yarn add react-router-dom@6
Step 2: The package installs after the completion of npm and a message is received on the terminal varying with your system architecture.
+ react-router-dom@6
added 11 packages from 6 contributors and audited 1981 packages in 24.897s
114 packages are looking for funding
run `npm fund` for details
found 0 vulnerabilities
And that’s it, we are ready to route!
Now let's come to the source code after the fundamental installation:
Source Code and Snippets
Step 1: After the installation of react-router-dom we can ensure that the package is successfully installed or not by checking the package.json file to see the installed react-router-dom module and its version.
{
"name" : "reactApp",
"version" : "1.0.0"
"description" : "It is.a react app"
"dependencies" : {
"react" : "^17.0.2",
"react-dom" : "^17.0.2",
"react-icons" : "^4.3.1",
"react-router" : "^6.2.1",
"react-router-dom" : "^6.2.1"
},
Step 2: Then you go straight to your index.js main page to activate BrowserRouter throughout the application running in the App.js file.
import {StrictMode } from "react";
import ReactDOM from "react-router-dom"
import App from "./App"
import {BrowserRouter} from "react-router-dom"
const rootElement = document.getElementById("root")
ReactDOM.render(
<StrictMode>
<BrowserRouter>
<App />
</BrowserRouter>
</StrictMode>,
rootElement
);
Step 3: Now, we can make directories for the components or the pages we want to render. Either you can make separate folders or can have one folder with all components. Using a terminal or with a new tab, folders can be created with ease.
mkdir src/components/Home
mkdir src/components/About
Now we will create a component inside each directory we created above. Here we will first create a Home.js file for the Home directory.
nano src/components/Home/Home.js
Then add the basic component rendering code for it.
function Home() {
return (
<div>
<h1> This is the home page </h1>
</div>
);
}
export default Home;
Followed by creating an About.js file for the About directory.
nano src/components/About/About.js
Then add the basic component rendering code for it.
function About() {
return (
<div>
<h1> This is the about page </h1>
</div>
);
}
export default About;
Step 4: Now come to the main App.js file which is the core of implementing all we have defined and declared till now by defining routes for each component and where and which component they will render when the path matches with the base URL entered or clicked by the user.
import {Routes , Route } from "react-router-dom"
import Home from "./components/Home/Home"
import About from "./components/About/About"
function App(){
return (
<div className="App">
<Routes>
<Route path="/" component={<Home/> } />
<Route path="/about" component={<About/> } />
</Routes>
</div>
)}
export default App
This is how we install and set up the basic boilerplate using React Router. After that, it can be extended with its components navigating with respect to website requirements.
React Router: Challenges and Debugging
React Router is simple to use if you follow and understand its basic template of it.
The challenges involved when you installed it on the terminal and tried to activate BrowserRouter but then also routing did not happen. Debugging comes with hands-on practice when you code the concept you visualize with the understanding of the concept learned here.
Have <Link> component inside <BrowserRouter> component because let's say if you have Header.js component with code :
import React from 'react'; import { Link } from 'react-router-dom'; const Header = () => { return ( <div className="App"> <Link to="/" > Home </Link> <Link to="/" > HomePage </Link> </div> ); };
and App.js with the rendering looks like :
import React from 'react'; import { BrowserRouter, Route, Link } from 'react-router-dom' import Home from "./components/Home/Home" import About from "./components/About/About" import Header from './Header'; const App = () => { return ( <div > <Header /> <BrowserRouter> <div> <Route path="/" exact component={Home} /> <Route path="/about" exact component={About} /> </div> </BrowserRouter> </div> ); }; export default App;
Here Header.js is using the <Link> component in the Header.js file but <Header> is placed outside <BrowserRouter> in app.js file making the error displayed: “component that is not the child of <Router> cannot contain its components as well.
Route is the child component of Routes, it must be used like taking Routes as parent component. Here the problem lies in the react-router version installation, react router 6 version does not allow Route to render without wrapping it up in Routes parent component just like:
function App() { return ( <div> <Routes> <Route path="/Contact" element={<Contact />} /> <Route path="/shop" element={<Shop/>} /> </Routes> </div> ); }
- Do not use anchor tags instead of <Link> components because using anchor tags would not allow applications to remain Single Page Application ( SPA). HTML anchor tag would trigger a page reload or page refresh when clicked.
Use the default Route always at the end while using switch components. Default Route is in the form of Redirect or Navigate in react router-dom@6 version.
Redirection happens when a login button is clicked on the Profile page redirecting you to <Login> component. Now <Redirect> is deprecated and {useNavigate} is currently in use with react-router latest version.
import React from "react" import {useNavigate} from "react-router-dom" export default function Profile() { let navigate = useNavigate() return ( <div> <h2> This is profile </h2> <button> onClick ={()=>{ navigate("/about")}}> Login </button> </div> );
Routes are used rather than switches in react-router-dom@6 install
<BrowserRouter> <Routes> <Route path="/" element={<Component />}> </Route> </Routes> </BrowserRouter>
exact keyword must be used to match the component's route paths precisely. If we have code somewhere like this:
<BrowserRouter> <Switch> <Route path="/" component={Home} /> <Route path="/home" component={Main} /> </Switch> </BrowserRouter>
The problem lies here with the Home Route which is the base route. React is needed to tell other routes are also appending with the “/” using exact.
<Route exact path="/" component={Home} />
How to Use React Router in Typescript
React-Router@5 is generally used for routing generally, but React-Router@6 is great for typescript programmers shipping type definitions. With packages installed react-router with typescript quick starts normally.
- npm install react-router-dom
- npm install @types/react-router-dom
Typescript is an extension of JavaScript, adding one good layer of safety and typing into the existing code, typing makes it easy for programmers to trace the problem.
React Router Examples
React Router can be implemented in any case where the primary requirement is to navigate. Navbars, User Registration and Login can be implemented too.
The segregation of components into their pages is considered to be react routing best practices.
Step 1: Activate BrowserRouter in index.js file
import {StrictMode } from "react";
import ReactDOM from "react-router-dom"
import App from "./App"
import {BrowserRouter as Router} from "react-router-dom"
const rootElement = document.getElementById("root")
ReactDOM.render(
<StrictMode>
<BrowserRouter>
<App />
</BrowserRouter>
</StrictMode>,
rootElement
);
Step 2: Make different components to render on routing: Home, Wishlist, Cart, No Match.
import React from "react"
function Home() {
return (
<div>
<h1> This is the home page </h1>
</div>
);
}
export default Home;
import React from "react"
export default function Cart() {
return <h1> This is Cart </h1>
}
import React from "react"
export default function WishList() {
return <h1> This is Wishlist </h1>
}
import React from "react"
export default function NoMatch() {
return <h1> This is 404 </h1>
}
Step 3: Route them in app.js file accordingly
import "./styles.css";
import {Routes , Route } from "react-router-dom";
import Home from "./pages/Home";
import Cart from "./pages/Cart";
import WishList from "./pages/WishList";
import NoMatch from "./pages/NoMatch";
import {Link} from "react-router-dom";
export default function App() {
return (
<div className="App">
<nav>
<Link to ="/"> Home </Link> ||
<Link to ="/cart"> Cart </Link> ||
<Link to ="/wishlist"> Wishlist </Link>
</nav>
<Routes>
<Route path ="/" element= {<Home />}/>
<Route path ="/cart" element= {<Cart />}/>
<Route path ="/wishlist" element= {<WishList />}/>
<Route path ="*" element= {<NoMatch />}/>
</Routes>
</div>
);
}
The react router navbar would look like this:
Different Types of Routers in React Router
React Routers gives us 3 types of routing in reactJS-
1. Browser Router
It is the most common type and most used type of router that uses HTML5 history API (pushState, replaceState, and the popstate event) making your UI in sync with the URL.
2. Hash Router
As the name sounds this type of router uses the hash portion of the URL keeping your UI in sync with the URL.
3. Memory Router
A router that keeps the history of your “URL” in memory does not like to put it in the address bar. Often used but useful in testing and non-browser environments like React Native.
Components in React Router and their Explanation
React Router DOM in reactJS is categorized into three primary components :
1. Routers
As we know, react-router-dom is an npm package that helps in dynamic routing, and provides <BrowserRouter> and <HashRouter>.
A) BrowserRouter: It is one of the parent components that is used to store all <Route> components that basically instruct the react app to navigate the components based on the route requested by the client. It is usually given an alias name ‘Router’ for ease of reference. It allows us to frame a complete and proper URL for navigation. Also, an additional point includes BrowserRouter gives us an inch of pain to handle the different routes configurations on the server-side This matters when you need to deploy large-scale production apps.
The syntax works like:
<BrowserRouter
basename = {{optionalString}
forceRefresh={optionalBool}
getUserConfirmation={optionalFunc}
keyLength = {optionaNumber}
>
<App/>
</BrowserRouter>
- basename: The basename prop is used to provide a base URL path for all the locations in the application.
- forceRefresh: It is a Boolean prop when set to true, refreshes and reloads the entire page with any route navigated across the same page.
- getUserConfirmation: A function that is used to confirm navigation but by default windows confirm it with window.confirm().
- keyLength: Location is a client-side library that allows us to implement routing, each location has the unique key but by default the key length: 6
The fundamental react router dom example is as follows:
import "./styles.css"
import {BrowserRouter} from "react-router-dom"
import {Routes, Route} from "./pages/Home"
import ProductDetail from "./pages/ProductDetail"
export default function App( ) {
return
<BrowserRouter>
<div className ="App"/>
<Routes>
<Route path = "/" element = {<Home />} />
<Route path = "/product-detail" element = {<ProductDetail />} />
</Routes>
</div>
</BrowserRouter>
)
HashRouter: It is the same as BrowserRouter but covers the two disadvantages of it when the BrowserRouter is not able to handle some old legacy servers or static servers like GitHub Pages, then HashRouter replaces it. As the name suggests, it first and foremost adds # to the forming base URL, it is used when there is no dependency on server-side configurations. It is just a # that is added between domain and path, and due to no dependency on history API, it works well in legacy servers. Also as it does not send anything written after # to the server request for say: https:// localhost:3000/#/about, the request will always go to / in the server, making the server happy to handle one single file only and the rest route path is handled at client side only to navigate the client to correct the route instantly.
2. Route Matchers
They are the matchers to navigate clients to and from the correct URL requested for using:
a. Route: It is the most basic component that maps location to different react components to render a specific UI when the path matches the current URL. It is an alternative to an if-statement logic for saying if want to go to the requested /about the path, the route is responsible for rendering that specific component matching across the current URL like <Route path =”/about” component ={ About }/>
<Route path ="/" component={<Home />} />
<Route path ="/about" component={<About />} />
<Route path ="/blogs" component={<Blogs />}/>
b. Switch: This component works similarly to the switch statement. It cuts down the exhaustive checking of each route path with the current URL instead the switch once gets the correct route path it returns back from there instead of checking till the last route path is written.
import {BrowserRouter , Switch, Route } from "react-router-dom"
<Switch>
<Route path ="/" component={<Home />} />
<Route path ="/about" component={<About />} />
<Route path ="/blogs" component={<Blogs />}/>
</Switch>
Route Changers: There are three types of navigators or route changes :
- Link: It is one of the primary ways to navigate the routes instead of putting it in the address bar you render it on UI as fully accessible just like anchor <href> tags of HTML with the main difference of anchor tags reload the UI to navigate, but links do not reload it again
- NavLink: It is an extended version of Link such that it allows us to see whether the
< Link > is active or not. This component provides isActive property that can be used with the className attribute.
3. Redirect: It is a kind of force navigation that will redirect user to the specific page programmers want if such a route is yet not present in the application to navigate forward to. It is a substitute for 404 error pages depending on the website requirement. It exists to have a strong use-case when user signs up on any web-application he is automatically redirected to the login page making UI experience more efficient.
<Switch>
<Link to ="/home"> Home </Link>
<NavLink to ="about" className={({ isActive }) =>
(isActive ? 'active': 'inactive')}>About</NavLink>
<Route path="/" component={<Home/>} />
<Route path="/about" component = {<About/>} />
</Switch>
What is the Difference Between React Router and React Router DOM?
These two seem identical. react-router is the core npm package for routing, but react-router-dom is the superset of react-router providing additional components like BrowserRouter, NavLink and other components, it helps in routing for web applications.
Conclusion
Till now we learned the basics and fundamentals of react router and its routing mechanism to start and how it helps to render specific components on the go in web applications. The more you extend towards the application requirement the more specific use-case can be drawn from it. The crux of the reactJS router works same in react router class component as well , just the syntax differences can be seen.
Are you looking forward to learning to react from scratch? Check out the React.js certification course from upGrad, and pick the right one that best suits your interest.
Start your journey with our free Software Development Courses. Find the right program for your goals below.
Explore Our Software Development Free Courses
Develop core in-demand Software Development skills to boost your career. Discover our skill pages below for practical learning.
In-Demand Software Development Skills
Frequently Asked Questions (FAQs)
1. Which Router is best for React JS?
Generally, BrowserRouter works best for building learning projects and small scale web-applications. It is just suited less at the production level due to its unavailability in legacy servers ending it up with a Cannot GET Route error plus it needs server configuration for every route created at the client side. Hence extra configuration at the server side plus limitation to SPA(Single Page Application) exists.
2. Do we need a React Router with the next JS?
Generally, react-router-dom is an npm package installed for routing but nextJS has its own inbuilt router giving ease of routing with next / link using which navigation is implemented.
3. What is the difference between a router and a switch?
The switch works just as the switch statement, by going through each and every route but once it matches the current URL with the route path, it returns back from there rendering that route component specifically. But Router is a standard library under which the switch is a component that helps users to navigate via the implementation of routing in web applications.
4. How do I enable routing in React?
Routing in react is easily enabled while installing react-router-dom npm package and then you are good to go for ease of navigation .
RELATED PROGRAMS