Skip to content

Mastering React Router Dom for Seamless Navigation

In the world of web development, efficient navigation is crucial for creating seamless user experiences. React Router Dom stands out as a powerful tool for managing navigation and routing in React applications. Whether you’re building a single-page application (SPA) or a multi-page app, React Router provides a declarative way to handle routes and transitions between views. What follows are the fundamentals of React Router, its key features, and how to integrate it into your projects.

Why Use React Router?

  • Declarative Routing: Define routes using JSX for a more intuitive approach, making the code easier to read and maintain.
  • Nested Routes: Create complex UIs with nested routes that match different parts of your app, allowing for more modular and organized code.
  • Dynamic Routing: Render components based on URL parameters, enabling dynamic content rendering.
  • Browser and Hash Routing: Support for both browser history and hash-based routing ensures flexibility in deployment.
  • Easy Navigation: Use components like <Link> to navigate within your app, improving user experience and accessibility.

Setting Up React Router

Step 1: Install React Router Dom

npm install react-router-dom

Step 2: Setting up Basic Routes

To set up routing in a React application, you’ll use the <BrowserRouter> component to wrap your application and define routes using the <Routes> and <Route> components.

And to navigate we use a Link. Now let’s understand what a Link is.

Step 3: Understanding <Link> in React

A <Link> is an element that lets the user navigate to another page by clicking or tapping on it. In react router dom, a <Link> renders an accessible <a> element with a real href that points to the resource it’s linking to. This means that things like right-clicking a <Link> work as you’d expect. You can use <Link reloadDocument> to skip client side routing and let the browser handle the transition normally (as if it were an <a href>).

// src/App.js

import React from 'react';
import { BrowserRouter as Router, Routes, Route, Link } from 'react-router-dom';
import Home from './components/Home';
import About from './components/About';
import Contact from './components/Contact';
function App() {
  return (
    <Router>
      <div>
        <nav>
          <ul>
            <li>
              <Link to="/">Home</Link>
            </li>
            <li>
              <Link to="/about">About</Link>
            </li>
            <li>
    <Link to="/contact">Contact</Link>
            </li>
          </ul>
        </nav>
        <Routes>
          <Route path="/" element={<Home />} />
          <Route path="/about" element={<About />} />
          <Route path="/contact" element={<Contact />} />
        </Routes>
      </div>
    </Router>
  );
}
export default App;

Just create the simple components of home, contact and about. And this will work. Don’t forget to check imports in App.js.

Nested Routes

Nested routes allow you to define routes within other routes. This is useful for creating layouts with child components.

Managing Nested Routes with Outlet

An <Outlet> should be used in parent route elements to render their child route elements. This allows nested UI to show up when child routes are rendered. If the parent route matched exactly, it will render a child index route or nothing if there is no index route.

// src/components/Dashboard.js

import React from 'react';
import { Link, Outlet } from 'react-router-dom';
function Dashboard() {
  return (
    <div>
      <h2>Dashboard</h2>
      <nav>
        <ul>
          <li>
            <Link to="settings">Settings</Link>
          </li>
          <li>
            <Link to="profile">Profile</Link>
          </li>
        </ul>
      </nav>
      <Outlet />
    </div>
  );
}
// src/App.js (Add these routes inside <Routes>)
<Route path="/dashboard/*" element={<Dashboard />}>
  <Route path="settings" element={<Settings />} />
  <Route path="profile" element={<Profile />} />
</Route>

In this setup, the Dashboard component contains links to nested routes, and the Outlet component renders the nested route components.

Dynamic Routing

Dynamic routing in React Router allows components to render based on URL parameters, making your application more interactive and user-friendly.

// src/components/Article.js
import React from 'react';
import { useParams } from 'react-router-dom';
function Article() {
  const { id } = useParams();
  return <h2>Article ID: {id}</h2>;
}
export default Article;

// src/App.js (Add this route inside <Routes>)

// <Route path=”/article/:id” element={<Article />} />

In this example, we use the useParams hook to extract the id parameter from the URL and display it in the Article component.

Accessing Search Params

React Router allows you to access search parameters (query parameters) from the URL using the useSearchParams hook.

// src/components/SearchPage.js
import React from 'react';
import { useSearchParams } from 'react-router-dom';
function SearchPage() {
  const [searchParams] = useSearchParams();
  const query = searchParams.get('query');
  return <h2>Search Query: {query}</h2>;
}
export default SearchPage;
// src/App.js (Add this route inside <Routes>)
// <Route path="/search" element={<SearchPage />} />

In this example, if the URL is /search?query=react, the SearchPage component will display “Search Query: react”.

Programmatic Navigation

You can also navigate programmatically using the useNavigate hook.

// src/components/Login.js
import React from 'react';
import { useNavigate } from 'react-router-dom';
function Login() {
  let navigate = useNavigate();
  function handleLogin() {
    // Perform login logic here
    navigate('/dashboard');
  }
  return (
    <div>
      <h2>Login Page</h2>
      <button onClick={handleLogin}>Login</button>
    </div>
  );
}
export default Login;
// src/App.js (Add this route inside <Routes>)
// <Route path="/login" element={<Login />} />

Here, after a user logs in, they are redirected to the dashboard using the useNavigate hook.

Advanced Features of React Router

React Router also offers advanced features that can significantly enhance your application’s routing capabilities:

  • Code Splitting: Lazy load routes to improve performance by splitting your code into smaller chunks.
  • Custom Route Matching: Define custom route matching logic to handle complex routing requirements.
  • Redirects: Easily manage redirects to handle old URLs or to guide users based on their actions.

Wrapping it up 

React Router Dom is essential for any React developer aiming to create dynamic, responsive web applications. Its features like nested routes and dynamic routing make it a versatile tool. By integrating React Router, developers can enhance their applications’ navigation, improving user experience significantly.

Ready to enhance your React projects? Dive deeper into our professional services and see how we can help you implement React Router Dom for seamless navigation. 

Contact us now to learn more!

More like this:

Converting an Angular Application to React: A Step-by-Step

Converting an Angular Application to React: A Step-by-Step

Introduction Migrating an application from Angular to React is a significant task that requires careful planning. Whether you’re…
How WebAssembly is Revolutionizing Front-End Development

How WebAssembly is Revolutionizing Front-End Development

Introduction In the ever-evolving world of web development, achieving optimal performance and a smooth user experience is essential.…
Uncovering Next.js Essentials for Revolutionizing Web Development

Uncovering Next.js Essentials for Revolutionizing Web Development

Next.js, a robust open-source React framework, is designed to simplify modern web development. Its user-friendly interface and intuitive features…