React-Router-Dom-npm - Everything You Need to Know

React-Router-Dom-npm - Everything You Need to Know

03 Oct 2024
Beginner
864 Views
12 min read
Learn with an interactive course and practical hands-on labs

ReactJS Course

What is react-router-dom?

You must be aware of how react-router-dom works if you have used React several times, but for first-timers, remember their names. The react-router-dom library is important for React developers working on React Applications. It helps them with dynamic routing within web apps.

This React Tutorial will give a gist of the meaning of react-router-dom, react-router-dom example, and much more. To explore various exciting topics in React, enroll in our React Certification Training right now!

Read More: Top 50 React Interview Question & Answers

Building Single-Page Applications with React Router DOM

Single-page apps are a typical case for web development projects nowadays. This is because these are web applications meant to be in the user’s browser. Therefore, there is no need to reload them each time users click on links or do something else to make them more user-friendly. One of the most favored tools for managing routes within SPAs is react-router-dom. This library helps developers create navigable and dynamic user interfaces with ease. Let's explore its core concepts and see how to use it effectively.

Core Concepts of React Router DOM

In order to fully grasp the code, you need to know the fundamental aspects of react-router-dom: 

  • Routes—These are used specifically to determine the path that your app will use and choose which component to present according to a given URL.
  • Navigation- React Navigation allows users to move between different parts of the application without refreshing the page.
  • Components- react-router-dom provides several components that help set up and manage routing in a React application.

Using <BrowserRouter> and <Routes> to Set Up Routing

The first step in using react-router-dom is to set up the routing context with <BrowserRouter>. This component wraps your entire application and enables the use of the routing components.

import { BrowserRouter, Routes, Route } from 'react-router-dom';

function App() {
  return (
    <BrowserRouter>
      <Routes>
        {/* Define your routes here */}
      </Routes>
    </BrowserRouter>
  );
}

export default App;

Defining Routes with the <Route> Component

Within the <Routes> component, you define individual routes using the <Route> component. Each <Route> specifies a path and the component to render when the path is matched.
import Home from './Home';
import About from './About';

function App() {
  return (
    <BrowserRouter>
      <Routes>
        <Route path="/" element={<Home />} />
        <Route path="/about" element={<About />} />
      </Routes>
    </BrowserRouter>
  );
}

Read More: 

Creating Navigation Links with <Link>

To enable navigation between different routes, react-router-dom provides the <Link> component. This works similarly to an HTML <a> tag but without causing a page reload.
import { Link } from 'react-router-dom';

function Navbar() {
  return (
    <nav>
      <Link to="/">Home</Link>
      <Link to="/about">About</Link>
    </nav>
  );
}

Handling Dynamic URLs with Route Parameters

Sometimes, dynamic URLs, such as user profiles or product pages, need to be handled. This is where route parameters come in handy.
import { useParams } from 'react-router-dom';

function UserProfile() {
  const { userId } = useParams();
  return <div>User Profile: {userId}</div>;
}

function App() {
  return (
    <BrowserRouter>
      <Routes>
        <Route path="/user/:userId" element={<UserProfile />} />
      </Routes>
    </BrowserRouter>
  );
}

Nested Routing for Complex UIs in React Router DOM

For more complex applications, you might need nested routes. react-router-dom supports this by allowing you to nest <Route> components within other routes.
function Dashboard() {
  return (
    <div>
      <h2>Dashboard</h2>
      <Routes>
        <Route path="stats" element={<Stats />} />
        <Route path="settings" element={<Settings />} />
      </Routes>
    </div>
  );
}

function App() {
  return (
    <BrowserRouter>
      <Routes>
        <Route path="/" element={<Home />} />
        <Route path="/dashboard/*" element={<Dashboard />} />
      </Routes>
    </BrowserRouter>
  );
}
Read More: React Developer Salary in India 2024 (For Freshers & Experienced)

Additional Features

React-router-dom also provides advanced features like redirects and route guards. 

1. Redirects

Redirects are helpful when you need to navigate users from one route to another automatically. This can be helpful when you've updated your route structure but still want to support old URLs. The <Navigate> component is used for this purpose.
import { Navigate } from 'react-router-dom';

function App() {
  return (
    <BrowserRouter>
      <Routes>
        <Route path="/" element={<Home />} />
        <Route path="/old-path" element={<Navigate to="/new-path" />} />
        <Route path="/new-path" element={<NewComponent />} />
      </Routes>
    </BrowserRouter>
  );
}

2. Route Guards

We utilize route guards to limit access to particular routes based on certain conditions, such as customer verification. They guarantee that only authenticated consumers can access protected areas within apps.

3. Custom Route Handling with use routes

The useRoutes hook in React allows you to define your routes more declaratively, which can be useful for managing complex route configurations.

4. Programmatic Navigation with us navigate

Sometimes, you might need to navigate programmatically based on certain events, like form submissions. The useNavigate hook provides this capability.

5. Lazy Loading with React.lazy

Lazy loading in React allows you to load components only as required, making your application perform well. React, lazy, and Suspense make this possible.
Conclusion
react-router-dom is a powerful library used for dynamic routing in React applications. By understanding its core components and features, you can build dynamic SPAs easily. Learn more about other various concepts of React Development by enrolling in our React Certification Course.

FAQs

react-router-dom is a library in React that helps in the dynamic routing within a web app.

You need to first, install the react-router and then, wrap your application with the BrowserRouter component. Now,use the Route component to define your routes and the Link component to easily navigate between them.

BrowserRouter sets the context for client-side routing and URL management while Route determines how particular components are displayed depending on the current URL or route.

React Router v6 uses hooks because of which class components like withRouter are deprecated in v6.

Take our React skill challenge to evaluate yourself!

In less than 5 minutes, with our skill challenge, you can identify your knowledge gaps and strengths in a given skill.

GET FREE CHALLENGE

Share Article
About Author
Shailendra Chauhan (Microsoft MVP, Founder & CEO at Scholarhat by DotNetTricks)

Shailendra Chauhan is the Founder and CEO at ScholarHat by DotNetTricks which is a brand when it comes to e-Learning. He provides training and consultation over an array of technologies like Cloud, .NET, Angular, React, Node, Microservices, Containers and Mobile Apps development. He has been awarded Microsoft MVP 9th time in a row (2016-2024). He has changed many lives with his writings and unique training programs. He has a number of most sought-after books to his name which has helped job aspirants in cracking tough interviews with ease.
Accept cookies & close this