Learn React, React

Implement Routing For Your React Apps With React Router

We will discuss these topics in this article:1) How does React Router work?2) What Justifies a React Router?3) How is React Router...

Written by Rohit Sharma · 5 min read >

We will discuss these topics in this article:
1) How does React Router work?
2) What Justifies a React Router?
3) How is React Router installed?
4) How is React Router configured?
5) Components in React Router
6) Link components are used to add navigation
7) React Router Advantages

How does React Router work?

Let’s start by understanding React’s routing. It is a procedure or a method of accessing the various sections or pages of the application according to the user’s request without refreshing the website.

The routing technique is supported by a React router, which is a tool or module built on top of React. The routes may be set up using this library, and when the user request matches, the corresponding route will be run, loading the relevant component.

What Justifies a React Router?

As I mentioned previously, every React application uses the renowned React router tool. The explanation is straightforward: we want to build a multi-page application, and the only way to browse those pages without refreshing the page is with the aid of a react-router.

Instead of utilizing React, we can develop non-single page applications using HTML and CSS if we want to create a program that doesn’t have several pages or views.

Do you think we can navigate to these pages without utilizing a routing framework, for instance, if we are building a one-page application that comprises many pages, such as Contact us, About us, and Services? No, is the response. In addition, any library used to build a single-page application uses one or more routing libraries to let users access various areas of the application. One such utility in the React framework is react-router. It is difficult to use the other features of the application without refreshing the webpage without a react-router.

How is React Router installed?

Three different routing packages are included in React router:
react-router: Includes the route matching algorithm, most of the basic components, and react hooks, making up the majority of the React Router’s fundamental functionality.
react-router-native: It is made for apps for mobile devices.
react-router-dom: It’s intended for use with web apps.

If you are using npm as your package manager, you can execute the following command from the root of your project to install a react-router:

npm install react-router-dom

This will install the most recent version of React Router V6, which is listed as a dependent in the package.json file. Installing a particular version requires appending the version to the end of react-router-dom@version-number.

You can execute the following command in its place if you are using yarn:

yarn add react-router-dom

How is React Router configured?

Installing the react-router makes setup simple as well. Each React application includes a <App> component as its Root component. This component has to be wrapped with the built-in <BrowserRouter> component from react-router-dom. React router is now accessible throughout the application once we’ve wrapped this up.

Every react application includes an index.js file, which serves as the application’s launchpad and bootstraps the <App> component. We can put the <BrowserRouter> component inside of this file.

The index.js file, which is included with every react application, is shown below.

import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
ReactDOM.render(
  <React.StrictMode>
    <App />
  </React.StrictMode>,
  document.getElementById('root')
);

The <BrowserRouter> component from react-router-dom can take the role of <React.StrictMode>. After we replace it, it will appear like this:

import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import { BrowserRouter } from "react-router-dom";
ReactDOM.render(
  <BrowserRouter>
    <App />
  </BrowserRouter>,
  document.getElementById("root")
);

The application now has routing available throughout. To access the various application sections, we can use the routing features.

Components in React Router

React router components are separated into three primary groups:

Routers – for instance, the components <BrowserRouter> and <HashRouter>

Route matchers – <Routes> and <Route> components, for instance.

Navigation – for instance, the components <Link> and <NavLink>

Routers

Every react router application is built on top of routers. Specifically created for web applications, React-router-dom offers the widely used <BrowserRouter>  and <HashRouter> components.

HashRouter

HashRouter’s real use case is when we are developing web applications without a need for a backend because when hashes are used in the URL, the browser does not perform a server request. This # will be parsed on the client side by the react-router.

<HashRouter
  basename={optionalString}
  getUserConfirmation={optionalFunc}
  hashType={optionalString}
>
  <App />
</HashRouter>

The base URL for all locations is basename, which is of type string. A basename that is correctly formatted should only include a preceding slash and no trailing ones.
Use the function getUserConfirmation to confirm navigation. using window.confirm by default.
The kind of encoding to use for the window.location.hash is hashType, which is of the string type.

BrowserRouter

It utilizes history API, therefore legacy browsers cannot use it (IE 9 and lower and contemporaries). A web server must support client-side React applications in order for them to keep clean routes like example.com/react/route. This often means that a web server should be set up for a single-page application, where the same index.html is provided for any server-side route, such as /react/route. React router parses window.location.pathname on the client side. A component that React Router had set up to render for /react/route is rendered.

Server-side rendering may also be used in the configuration, and rendered data or components tailored to the current route may be found in index.html.


import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import { BrowserRouter } from "react-router-dom";
ReactDOM.render(
  <BrowserRouter>
    <App />
  </BrowserRouter>,
  document.getElementById("root")
);

Route Matchers

<Routes> and <Route> are the two most crucial route matchers. <Routes> is a component that was added in version 6 and is a robust alternative for the <Switch> component. These parts will assist us in rendering the content on the webpage in accordance with user requests.

<Routes> examine every user request for the URL; if the URL matches, the corresponding <Route> is then carried out. Here, <Routes> serves as the parent, containing <Route> as its offspring.

<Route> requires the React props element and path. Path specifies the component’s url, while element houses the actual component that needs to be rendered.

import Home from "./Home"
import About from "./About"
import Contact from "./Contact"
function App() {
  return (
    <div className="App">
      <Routes>
        <Route path="/" element={ <Dashboard/> } />
        <Route path="services" element={ <Services/> } />
        <Route path="contact" element={ <Contact/> } />
      </Routes>
    </div>
  )
}
export default App

Navigation

React Router has many navigational elements including <Link> and <NavLink>.

Link: It is comparable to the HTML< a> element. By clicking on it, we can navigate to another view.

NavLink: A specific form of <Link> called a <NavLink> adds an active class by default when it becomes active. This is primarily used when creating a navigation menu with a list of links.

Using the Link Component to Add Navigation

As was previously mentioned, the HTML <a> element and <Link> are comparable. It is utilized to move between views or pages.

import { Link } from "react-router-dom";
function Dashboard() {
  return (
    <div>
      <h1>This is the home page</h1>
      <Link to="services"> The services listed below are what we provide </Link>
      <Link to="contact"> You can reach us by filling out a form</Link>
    </div>
  );
}
export default Home;

The prop is navigated to the destination URL/route using the <Link> component, which is enclosed in double quotes. When a user clicks a link, the react-router checks the URL against the <Routes>; if the two matches, the appropriate <route> is executed.

React Router Advantages

To keep the application in sync with the browser URL, client-side routing is needed.

• There are so many features available right away.
• We may make routing available across the application by using <BrowserRouter>.
• It uses <Link> to go to other views or pages.
• It renders using <Routes> and <Route>.
• It is mostly used for one-page applications.
• It is constructed using the React framework.

Conclusion

This article will help you for understanding the concept of React Routing. Thank you for reading my article.

Loading

2 Replies to “Implement Routing For Your React Apps With React Router”

Leave a Reply

Your email address will not be published. Required fields are marked *