Show List

React Router for navigation

React Router is a popular library for handling routing in React applications. It provides a simple way to declare the routes of an application and handle navigation between those routes. The library supports dynamic and nested routes, URL parameters, and much more.

Here's a simple example of how to use React Router to handle navigation in a React application:

import React from "react";
import {
  BrowserRouter as Router,
  Switch,
  Route,
  Link
} from "react-router-dom";

function Home() {
  return <h2>Home</h2>;
}

function About() {
  return <h2>About</h2>;
}

function Users() {
  return <h2>Users</h2>;
}

function App() {
  return (
    <Router>
      <div>
        <nav>
          <ul>
            <li>
              <Link to="/">Home</Link>
            </li>
            <li>
              <Link to="/about">About</Link>
            </li>
            <li>
              <Link to="/users">Users</Link>
            </li>
          </ul>
        </nav>

        <Switch>
          <Route path="/" exact component={Home} />
          <Route path="/about" component={About} />
          <Route path="/users" component={Users} />
        </Switch>
      </div>
    </Router>
  );
}

export default App;

In this example, we are using the BrowserRouter component from the react-router-dom library to wrap our application. This sets up a client-side router that handles navigation within the application.

We have defined three components, Home, About, and Users, which represent the different pages of our application. The navigation links between these pages are defined using the Link component from react-router-dom.

The Switch component is used to group a set of Route components together. The Route components define the different routes of the application and map a specific URL path to a component. The path prop of each Route component is used to match the current URL to the corresponding component.

In this example, the / path is matched to the Home component using the exact prop, which ensures that only the exact path is matched.

React Router provides a lot of additional features and options, such as URL parameters, query strings, and programmatic navigation. By understanding how to use React Router, you can build complex and dynamic navigation experiences in your React applications.


    Leave a Comment


  • captcha text