Instagram
youtube
Facebook
Twitter

React Router Basics

Introduction

In single-page applications (SPAs) built with React, managing navigation and URL-based routing is essential. React Router is a popular library that enables seamless navigation in React apps by allowing you to set up routes, manage URL parameters, and create dynamic routes. React Router makes it easy to link different parts of your application, providing users with a smooth and responsive navigation experience.

In this lesson, you’ll learn:

  • What React Router is and how it works
  • How to set up basic routes in a React application
  • Key components of React Router like BrowserRouter, Route, and Link

What is React Router?

React Router is a library that allows you to manage routes and navigation in React applications. It provides components and hooks that enable you to create different routes, which correspond to various sections or "pages" of your application. When a user navigates to a different route, React Router dynamically loads the appropriate component for that route, rather than reloading the entire page.

Why Use React Router?

  1. SPA Navigation: React Router supports seamless transitions between pages without refreshing the entire page.
  2. URL Management: React Router allows URL-based navigation, so each route has its own URL, making it easy to bookmark or share specific pages.
  3. Dynamic Routing: React Router enables dynamic routes based on parameters (e.g., user profiles, product pages) that update based on the URL.

Setting Up React Router

To use React Router, you’ll need to install the react-router-dom package, which provides routing components for web applications.

Step 1: Installing React Router

Run the following command in your project’s root directory:

npm install react-router-dom

Step 2: Importing Components

Once installed, you can start using React Router’s components by importing them into your project.


Core Components of React Router

React Router’s main components include:

  1. BrowserRouter: Wraps the entire app to enable routing.
  2. Route: Defines a route and the component it should render.
  3. Link: Provides navigation links for users to navigate between routes.

Let’s explore each of these components in detail.


BrowserRouter

The BrowserRouter component enables routing in your application and should be wrapped around your root component. It uses the browser's history API to keep the UI in sync with the URL.

Example: Wrapping the App with BrowserRouter

import React from 'react';
import ReactDOM from 'react-dom';
import { BrowserRouter } from 'react-router-dom';
import App from './App';

ReactDOM.render(
  <BrowserRouter>
    <App />
  </BrowserRouter>,
  document.getElementById('root')
);

In this example:

  • BrowserRouter wraps the <App /> component, allowing you to use routing components within your app.

Route

The Route component is used to define individual routes. Each route has a path that corresponds to a URL path and a component to render when the URL matches the path.

Syntax of Route

<Route path="/route-path" element={<Component />} />
  • path: Specifies the URL path that will trigger this route.
  • element: Specifies the component to render when the path matches.

Example: Defining Routes with Route

In your main app component, you can set up routes like this:

import React from 'react';
import { Routes, Route } from 'react-router-dom';
import Home from './components/Home';
import About from './components/About';
import Contact from './components/Contact';

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

export default App;

In this example:

  • A <Route /> is created for each path (/, /about, /contact) with a corresponding component (Home, About, Contact).
  • The Routes component wraps multiple Route components and is used to group all the routes in the app.

Link

The Link component allows you to create navigation links that users can click to navigate between routes without refreshing the page. The Link component replaces traditional <a> tags in SPAs, making navigation faster.

Syntax of Link

<Link to="/route-path">Link Text</Link>
  • to: Specifies the path to navigate to when the link is clicked.

Example: Using Link for Navigation

import React from 'react';
import { Link } from 'react-router-dom';

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

export default Navbar;

In this example:

  • Link components navigate to the specified routes (/, /about, /contact), and the page does not reload.
  • You can use Link to create a navbar or other navigation elements in your app.

Example: Putting It All Together

Here’s a full example of a basic React app with routing:

import React from 'react';
import { Link } from 'react-router-dom';

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

export default Navbar;
  • Components: Home, About, and Contact are simple components representing pages.
  • Routing: Routes are defined for each page using Route.
  • Navigation: Link components in the navbar provide navigation to each page.

Switching Routes Conditionally with Navigate

If you need to redirect users conditionally, you can use the Navigate component.

Example: Redirecting to a Different Route

import React from 'react';
import { Navigate } from 'react-router-dom';

function ProtectedRoute({ isAuthenticated }) {
  return isAuthenticated ? <Dashboard /> : <Navigate to="/login" />;
}

In this example:

  • ProtectedRoute redirects unauthenticated users to the /login route.
  • Navigate is a replacement for the Redirect component used in earlier versions of React Router.

React Router in Nested Components

React Router also supports nested routes, where you can define routes within sub-components. This is useful for applications with complex route structures, such as dashboards or multi-step forms.

Example: Nested Routes

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

function Dashboard() {
  return (
    <div>
      <h2>Dashboard</h2>
      <nav>
        <Link to="profile">Profile</Link>
        <Link to="settings">Settings</Link>
      </nav>
      <Routes>
        <Route path="profile" element={<Profile />} />
        <Route path="settings" element={<Settings />} />
      </Routes>
    </div>
  );
}

function App() {
  return (
    <Routes>
      <Route path="/dashboard/*" element={<Dashboard />} />
    </Routes>
  );
}

In this example:

  • Dashboard contains nested routes for profile and settings.
  • The path for the nested routes is relative, so Dashboard manages its sub-routes independently.

Conclusion

In this lesson, we covered:

  • The purpose and benefits of using React Router for navigation in SPAs
  • Core components such as BrowserRouter, Route, and Link
  • Examples of setting up basic routes and nested routes in React Router

With these basics of React Router, you’re now equipped to create a navigable React application. In the next lesson, we’ll explore more advanced routing topics, such as dynamic routing and route parameters, to make your application even more interactive and responsive to user input.