Handling router using react-router-dom with realtime example

React Router is a popular library for handling routing in React applications. It allows you to declare routes using components, and navigate between them using the <Link> and <Route> components. Here is an example of how to set up routing using React Router:

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

function App() {
  return (
          <Link to="/">Home</Link>
          <Link to="/about">About</Link>
          <Link to="/contact">Contact</Link>

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

In this example, we are first importing the Router, Route, and Link components from the react-router-dom library.

  • The <Router> component is used to wrap the entire application and provide a context for the routing.
  • The <Link> component is used to create a link to a specific route. In this example, we have three links, one for each of the routes we have defined.
  • The <Route> component is used to define a specific route that the application should navigate to when the corresponding link is clicked. In this example, we have three routes, one for the home page, one for the about page, and one for the contact page.

The path prop of the <Route> component is used to define the URL pattern that should match the route. The component prop is used to specify the component that should be rendered when the route is active. The exact prop is used to match the path exactly, so that only the home page will be displayed when the user is on the root path ‘/’.

It’s important to note that the components Home, About and Contact are assumed to be already defined in the codebase.

This is a basic example of how routing can be handled using React Router. You can also use other props like render, children and switch to handle routing. Additionally, you can also use withRouter higher-order component to access the router props and useParams hook to access dynamic parts of the URL.