React Router

React Router is a popular library for routing in React applications. It provides a declarative way to handle navigation and define routes in your application, allowing you to render different components based on the URL.

Here’s an overview of React Router:

  1. Installation:
    You can install React Router using npm or yarn:
   npm install react-router-dom

or

   yarn add react-router-dom
  1. Basic Usage:
    React Router provides several components to define routes in your application. The most commonly used components are BrowserRouter, Route, and Link.
  • BrowserRouter: Wraps your application and provides routing functionality.
  • Route: Defines a route and specifies which component to render when the URL matches the route path.
  • Link: Provides declarative navigation by rendering an anchor tag (<a>) that changes the URL when clicked.
  1. Example:
    Here’s a basic example of how to use React Router in your application:
   import React from 'react';
   import { BrowserRouter as Router, Route, Link } from 'react-router-dom';
   import Home from './Home';
   import About from './About';
   import Contact from './Contact';

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

                   <Route path="/" exact component={Home} />
                   <Route path="/about" component={About} />
                   <Route path="/contact" component={Contact} />
               </div>
           </Router>
       );
   }

   export default App;
  1. Nested Routes:
    React Router supports nested routes, allowing you to define routes within other routes. This is useful for creating complex application layouts with multiple levels of navigation.
  2. Route Parameters:
    You can use route parameters to match dynamic segments of the URL and pass them as props to the rendered components.
  3. Programmatic Navigation:
    React Router provides a history object that allows you to perform navigation programmatically, such as pushing, replacing, or going back and forth in the browser history.

React Router simplifies navigation and routing in React applications, making it easy to create single-page applications with multiple views and layouts. It’s a powerful tool for building complex user interfaces with client-side routing functionality.