React Router DOM: How to handle routing in web app

React Router DOM is an npm package that enables us to implement dynamic routing in a web app. It allows you to display pages and allow users to navigate them. It is a fully-featured client and server-side routing library for React. React Router Dom is used to build single-page applications i.e. applications that have many pages or components but the page is never refreshed instead the content is dynamically fetched based on the URL. This process is called Routing and it is made possible with the help of React Router Dom.

The major advantage of react-router is that the page does not have to be refreshed when a link to another page is clicked. This means that the user experience is better and the app has overall better performance.

React Router Dom has many useful components and to create fully functioning routing, you need most of these.

  1. Router(usually imported as BrowserRouter): It is the parent component that is used to store all of the other components. Everything within this will be part of the routing functionality

  2. Routes: Routes component is used to render only the first route that matches the location rather than rendering all matching routes.

  3. Route: This component checks the current URL and displays the component associated with that exact path. All routes are placed within the switch components.

  4. Link: Link component is used to create links to different routes.

Example:

component:1

import React from 'react'

export default function Page1() {
    return (
        <div>
            <h1>Page 1</h1>
        </div>
    )
}

component:2

import React from 'react'

export default function Page2() {
    return (
        <div>
            <h1>Page 2</h1>
        </div>
    )
}

component:3

import React from 'react'

export default function Page2() {
    return (
        <div>
            <h1>Page 3</h1>
        </div>
    )
}

App.js

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

// Import the pages/Components

import Page1 from "./Components/page1"
import Page2 from "./Components/page2"
import Page3 from "./Components/page3"

// Import css
import "./app.css"

function App() {
  return (
    <div className="App">
      <Router>
        <Routes>
          <Route exact path="/" element={<h1>Home Page</h1>} />
          <Route exact path="page1" element={<Page1 />} />
            <Route exact path="page2" element={<Page2 />} />
          <Route exact path="page3" element={<Page3 />} />
        </Routes>
        <div className="list">
          <ul>
            <li><Link to="/">Home</Link></li>
            <li><Link to="page1">Page 1</Link></li>
            <li><Link to="page2">Page 2</Link></li>
            <li><Link to="page3">Page 3</Link></li>
          </ul>
        </div>
      </Router>
    </div>
  );
}
export default App;