React Router: Installation and Configuration


  React Router is a library that allows you to add navigation to your React applications. In this lesson, you'll learn how to install and configure React Router to manage routes in your project.


How to Install React Router?

  To use React Router in your React project, you first need to install the library using npm or yarn. Run the following command in your project's terminal:


npm install react-router-dom

  After installation, you can start using the components that React Router provides.


Basic React Router Configuration

  Once React Router is installed, the next step is to configure the routes within your application. You need to wrap your application in the BrowserRouter component and then define the routes using the Route component.


  • BrowserRouter: This component allows your application to use the browser's history to handle routes declaratively.
  • Route: The Route component is used to define which components should be displayed based on the application's URL.

  Let's look at a basic example:

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

const App = () => {
  return (
    <Router>
      <Switch>
        <Route path="/" exact>
          <Home />
        </Route>
        <Route path="/about">
          <About />
        </Route>
      </Switch>
    </Router>
  );
};

Navigation with Links

  To navigate between routes, you can use the Link component instead of traditional HTML <a> tags. This allows your application to avoid a full page reload, making navigation smoother.


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

const Navigation = () => {
  return (
    <nav>
      <ul>
        <li><Link to="/">Home</Link></li>
        <li><Link to="/about">About</Link></li>
      </ul>
    </nav>
  );
};

  Remember that by using Link, navigation will be more efficient as React Router will take care of updating only the necessary parts of the interface.


Dynamic Routes with Parameters

  React Router also allows you to define dynamic routes that can receive parameters in the URL. This is useful when you want to display content based on a specific identifier, such as an article or a user.


<Route path="/user/:id" component={User} />

  In this example, :id is a dynamic parameter that you can access within the User component.



React Router-example React Router-dom documentation React Router v6 React Router v7 React-router - npm Install react-router-dom React Router alternatives TanStack Router