React Routers DOM

React Routers DOM

·

4 min read

Introduction

React Router is a popular library in the ReactJs that enables navigation and routing functionality in React applications. It allows you to create single-page applications with multiple views and URLs, similar to traditional multi-page applications. With the help of Routers you can easily navigate to another Pages and It provides some of the router hooks such as useHistory, useLocation and useParams we will go through with this react hooks in this blog.

Installation:

npm install react-router-dom
or
yarn add react-router-dom

Router Component:

Import the BrowserRouter from the react-router-dom wrap it around the your App component.The BrowserRouter component is the top-level component provided by React Router.

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

ReactDOM.render(
  <BrowserRouter>
    <App />
  </BrowserRouter>,
  document.getElementById('root')
);

Routes Components

import { Routes,Route} from 'react-router-dom';      

      <Routes>
        <Route path="/" element={<Home/>}/>
        <Route path="/about" element={<About/>}/>
        <Route path="/contact" element={<Contact/>}/>
      </Routes>

The Routes component is a container that wraps one or more Route components. It allows you to define the routing configuration for your application. It is typically used as the top-level component for defining routes in your application.

The Route component is used to define an individual route and its associated component. It specifies the URL path for which the component should be rendered. When the current URL matches the specified path, the corresponding component is rendered.

Navigation:

React Router provides the Link component for creating navigation links. It renders an anchor tag <a> with a proper URL, allowing users to navigate between different routes without full page reloads.

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

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

The import {Link} from the 'react-router-dom' statement imports the Link component from the react-router-dom package. The Link component is used to create navigation links in your application. Each navigation item is represented by a list item <li>. Within each <li>, a Link component is used to create a clickable link. The to prop of the Link component specifies the target URL to navigate to when the link is clicked. For example, <Link to="/about">About</Link> would navigate to the "/about" route when the "About" link is clicked.

React Router Hooks:

Here are some of the important hooks provided by React Router for handling routing in React applications such as useHistory, useLocation and useParams. we will look into each of these React Router Hooks.

useHistory:

useHistory hook provides access to the history object, which allows you to navigate programmatically and manipulate the browser history.

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

function MyComponent() {
  const history = useHistory();

  const navigate = () => {
    history.push('/new-route');
  };

  return (
    <div>
      <button onClick={navigate }>Go to New Route</button>
    </div>
  );
}

Within the MyComponent component, the useHistory hook is called to get access to the history object. The history object provides several methods for navigation and history management, such as push, replace and goBack. In this example, the navigate function is triggered when the button is clicked. It uses history.push() method to navigate to the "/new-route" URL. The history.push() method updates the URL and triggers navigation to the specified route without causing a full page to reload. It maintains the single-page application behaviour.

useLocation:

useLocation hook provides access to the current location object, which contains information about the current URL path, search parameters, and more.

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

function MyComponent() {
  const location = useLocation();

  return (
    <div>
      <p>Current Path: {location.pathname}</p>
      <p>Search: {location.search}</p>
      <p>Hash: {location.hash}</p>
    </div>
  );
}

Within the MyComponent component, we call the useLocation hook to get access to the location object. The location object contains various properties, such as pathname, search, and hash, which provide information about the current URL. In the example, we render three paragraphs to display different details of the current location. The location.pathname property represents the current URL path. The location.search property represents the query string parameters of the URL.

useParams:

useParams hook allows you to access route parameters defined in the URL. It returns an object containing key-value pairs of the parameter names and their values.

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

function UserDetail() {
  const { id } = useParams();

  return (
    <div>
      <h2>User ID: {id}</h2>
      {/* Rest of the component */}
    </div>
  );
}

Within the UserDetail component, we call the useParams hook and destructure the id parameter from the returned object. In the example, we render an <h2> element that displays the value of the id parameter extracted from the URL. You can use the id parameter within the component to perform further logic, such as fetching user data based on the ID or displaying dynamic content specific to the user with that ID.

Conclusion:

In this blog, we have explored the 'react-router-dom' package, which provides powerful routing capabilities for React applications. We discussed how React Router helps in navigating between different pages without causing full-page reloads, thereby creating a seamless single-page application experience. We explored three important React Router hooks useHistory, useParams and useLocation. These hooks provide additional functionalities and access to route-related information.