React Router

Posted July 28, 2023 by Rohith and Anusha ‐ 5 min read

In the realm of modern web development, creating dynamic and responsive single-page applications (SPAs) has become the norm. Users expect seamless transitions and smooth navigation between various components without experiencing the traditional page reloads. To cater to this demand, the React ecosystem offers a powerful and flexible solution known as React Router.

What is React Router?

  • React Router is a popular library built specifically for React applications to handle routing and navigation seamlessly.

  • It enables developers to create SPAs with multiple views and helps in managing the application’s UI based on the URL.

  • With React Router, you can develop web applications with a more traditional multi-page feel while still being an SPA under the hood.

Why React Router?

  • In a typical React application, navigation is not handled by the traditional browser methods like clicking on anchor links or submitting forms.

  • Instead, React Router provides a declarative way to manage navigation, making it easier to define what should be displayed based on the URL.

Here are some key benefits of using React Router:

Declarative Routing

  • React Router allows developers to describe the application’s UI based on the URL.

  • It employs a declarative approach, where you define the routing rules and components to render for specific URLs.

Nested Routing

  • React Router supports nested routes, meaning you can have different components render within other components, creating a hierarchy of views.

History Management

  • React Router handles browser history manipulation, enabling users to use the back and forward buttons seamlessly, just like in a multi-page application.

Dynamic Routing

  • You can create dynamic routes with React Router, meaning you can pass parameters in the URL and extract them to render the appropriate components.

Code Splitting

  • React Router plays well with code splitting, allowing you to load only the necessary components for a particular route, improving the application’s overall performance.

Getting Started with React Router

To begin using React Router in your React application, you need to install it as a dependency:

npm install react-router-dom

Now, you can start defining your application’s routes and navigation logic.

The primary components provided by React Router are:

BrowserRouter

  • This component uses HTML5 History API to keep the UI in sync with the URL.

Route

  • This component associates a path with a specific component to render when the URL matches that path.
  • Instead of using regular anchor tags (<a>), React Router provides the Link component for navigation.

  • It prevents full-page reloads and provides a smoother experience.

Example

Let’s create a simple example of React Router to understand how it works:

// Import required modules
import { BrowserRouter, Route, Link } from "react-router-dom";

// Define components for different routes
const Home = () => <h1>Welcome to the Home Page</h1>;
const About = () => <h1>About Us - We are Awesome!</h1>;

// App component
const App = () => {
  return (
    <BrowserRouter>
      <nav>
        <ul>
          <li>
            <Link to="/">Home</Link>
          </li>
          <li>
            <Link to="/about">About</Link>
          </li>
        </ul>
      </nav>
      <Route exact path="/" component={Home} />
      <Route path="/about" component={About} />
    </BrowserRouter>
  );
};

Output

  • When you run the app and access it in the browser, you will see a simple navigation bar with two links: Home and About.

  • Clicking on each link will display the corresponding component below the navigation bar.

  • When you access the root URL (/), the Home component will be rendered, and you will see the text Welcome to the Home Page displayed on the screen.

  • When you click on the About link, the URL will change to /about, and the About component will be rendered, showing the text About Us - We are Awesome! on the screen.

  • In this example, we have set up two routes using the Route component, one for the home page and another for the about page.

  • We also used the Link component to create navigation links.

Nested Routing with React Router

React Router allows you to have nested routes, which can be useful for organizing complex UI structures.

For example

// Nested Routing Example
const Dashboard = () => <h1>Welcome to the Dashboard</h1>;
const UserProfile = () => <h2>User Profile Page</h2>;

const App = () => {
  return (
    <BrowserRouter>
      {/* Navigation Links */}
      <nav>
        <ul>
          <li>
            <Link to="/">Home</Link>
          </li>
          <li>
            <Link to="/dashboard">Dashboard</Link>
          </li>
          <li>
            <Link to="/dashboard/profile">Profile</Link>
          </li>
        </ul>
      </nav>

      {/* Routes */}
      <Route exact path="/" component={Home} />
      <Route exact path="/dashboard" component={Dashboard} />
      <Route path="/dashboard/profile" component={UserProfile} />
    </BrowserRouter>
  );
};

Output

  • Upon running the app and accessing it in the browser, you will see the navigation bar with three links: Home, Dashboard, and Profile.

  • Clicking on each link will display the corresponding component below the navigation bar.

  • When you access the root URL (/), the Home component will be rendered, and you will see the text Welcome to the Home Page displayed on the screen.

  • When you click on the Dashboard link, the URL will change to /dashboard, and the Dashboard component will be rendered, showing the text Welcome to the Dashboard on the screen.

  • When you click on the Profile link, the URL will change to /dashboard/profile, and the UserProfile component will be rendered, showing the text User Profile Page on the screen.

Conclusion

  • React Router is an essential tool for building modern React applications with smooth and efficient navigation.

  • Its declarative approach, support for nested routes, and easy history management make it a powerful choice for handling routing needs in SPAs.

  • By using React Router, you can create a delightful user experience, allowing users to seamlessly explore and interact with your application without the need for page reloads.

quick-references blog react-router react-library

Subscribe For More Content