Computer scienceFrontendReactReact Router

Introduction to React Router

8 minutes read

React-router is a key tool for developers building web applications with React. It makes creating single-page applications (SPAs) easier by effectively managing navigation between various components. React-router supports dynamic, client-side routing, allowing for updates to URLs and content changes without the need for standard page refreshes. This results in a smooth, app-like user experience. In this topic, you will explore the fundamental concepts of React-router and learn how to integrate it efficiently into your React projects.

What is React Router?

React-router is a tool that manages the behavior of a React application when the user interacts with the browser's address bar. While navigating websites, usually clicking on different links leads to loading a new page. But, React-router enables smooth, quick transitions between different "pages" or sections of a website without needing to reload the entire page with each click. It's similar to browsing through a book's pages instead of switching books for each new page. This feature makes websites faster and provides a more application-like experience.

For websites with multiple sections or pages functioning as a single application, React-router is especially useful. It keeps track of the "page" you are currently viewing, keeping you on the correct page even after refreshing the browser. This tool is a must-have for contemporary web applications requiring speed and efficiency, and that's why many developers include React-router in their projects.

Installing React Router

To begin using React-router in your project, you need to install it. Do this by running the following command in your terminal:

npm install react-router-dom

Running this command adds the react-router-dom package to your project. This package provides the necessary components for routing in web applications.

After installing, confirm its addition by checking your package.json file. Look for an entry in the dependencies section that looks like this:

"dependencies": {
    "react": "^18.2.0",
    "react-dom": "^18.2.0",
    "react-router-dom": "^6.20.1"
  },

If you see this, it means that the react-router-dom has been successfully installed in your application.

Understanding React Router's components

React-router uses various components to define and manage routes within your application:

  • Router: it's the main component that encapsulates and provides a context for all other routing components.

  • Routes: acts as a container for Route components, defining possible paths and corresponding components.

  • Route: it represents a single path and the component to render when that path is accessed.

After installing React-router, import it into your application. Add the line below to your App.jsx file to do so:

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

React-router provides <BrowserRouter> and <Route> components to set up routing in the React application.

import { BrowserRouter as Router, Route, Routes } from "react-router-dom";
import Home from './components/Home';
import About from './components/About';

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

export default App;

In the example, BrowserRouter is renamed Router for simplicity's sake. Inside the App component, a Router component is returned as a wrapper for all the application's routes. The Routes component defines the application's various routes, acting as a container for all Route components.

Two Route components are specified within the Routes component. Each Route component represents a different route or page in the application. To demonstrate diverse navigation pages, create the Home.jsx file and the About.jsx file.

  • The first Route, with a path of /, is associated with the Home component, indicating that the Home component will appear when users visit the root URL (/).

import React from "react";

const Home = () => {
  return (
    <div className="flex items-center justify-center h-full w-full mt-40">
      <p className="text-[24px] font-bold">Hi, I am home now</p>
    </div>
  );
};

export default Home;

Home page

  • The second Route, with a path of /about, is associated with the About component. This means the About component will be rendered when users navigate to the /about URL.

import React from "react";

const About = () => {
  return (
    <div className="flex items-center justify-center h-full w-full mt-40">
      <p className="text-[24px] font-bold">Now this is all about me</p>
    </div>
  );
};

export default About;

About page

Understanding the exact prop

In versions of React Router before v6, the exact prop is used in the Route component to ensure that the component only loads when the URL path perfectly matches the route specified. This is important because React Router uses a matching algorithm that by default performs partial matching. Without the exact prop, a route defined with the path / would match any URL, since all URLs begin with /. Let's look at these routes for instance:

<Route path="/" component={<Home />} />
<Route path="/about" component={<About />} />

Without the exact prop, both routes would match the URL path /about; this would lead to the Home and About components both being rendered. But if we add the exact prop to the first route:

<Route exact path="/" component={Home} />

Now, the Home component only renders when the URL path equates to exactly /, and not when it is /about.

Using the exact prop can be very useful when you want to avoid multiple components rendering for closely related routes and want to ensure only the right component loads for the exact URL path.

Benefits of react-router

React-router substantially enhances both the user experience and development process of web applications with several key features:

  • Seamless navigation: React-router lets you move between different sections or "views" of an application without fully reloading the page, resulting in smoother transitions similar to those in native desktop applications.

  • Dynamic content loading: By dynamically loading content based on your navigation path, it makes applications feel more interactive and efficient.

  • Client-side routing: React-router works on the client side, allowing for instant responses to user actions and bypassing the slower process of server-side routing. This method enhances the user experience with quicker interactions, while also lessening server load and network traffic.

  • State preservation: React-router helps in preserving the application's state as you navigate through the application. In other words, your actions and the application data remain consistent and intact throughout your journey.

By utilizing these benefits, React-router serves as a sturdy solution for the development of feature-rich, user-friendly single-page applications.

Conclusion

Throughout this topic, you have learned React-router and its role in enhancing the navigation of single-page applications. By integrating React-router, you can ensure seamless transitions between components, dynamic content loading, and the preservation of the application state. These features contribute to creating a more interactive and user-friendly experience in your React applications. Have fun while working and practicing setting up routes, navigating between views, and exploring advanced configurations. The more you work with React-router, the more comfortable you'll become with its capabilities.

3 learners liked this piece of theory. 0 didn't like it. What about you?
Report a typo