Signup/Sign In

React Routers

ReactJS is quite a popular javascript library nowadays when dealing with the user interface of single-page applications. With the support of React Router, we can also use it to build multi-page applications. This is a third-party library that allows our React apps to path. The router very efficiently holds the app's user interface and URL in sync.

This guide will show you how to set up routing for an app using React Router v5.

Setting up React Router

First, we need to install the router, for that you need to write the following command in your terminal:

npm install react-router

Secondly, we need to create a new React app by running the following command in your terminal:

npx create-react-app react-router-guide

Let's add some lines of code to your App.js.

import React from "react";
import "./index.css"

export default function App() {
  return (
    <main>
      <nav>
        <ul>
          <li><a href="/">Home</a></li>
          <li><a href="/about">About</a></li>
          <li><a href="/contact">Contact</a></li>
        </ul>
        </nav>
     </main>
  );
}
// Home Page
const Home = () => (
  <Fragment>
    <h1>Home</h1>
    <FakeText />
  </Fragment>
  );
// About Page
const About = () => (
  <Fragment>
    <h1>About</h1>
    <FakeText />
  </Fragment>
  );
// Contact Page
const Contact = () => (
  <Fragment>
    <h1>Contact</h1>
    <FakeText />
  </Fragment>
  );

const FakeText = () => (
  <p>
  Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
  </p>
  )

Now, you're ready to set up the router in the next step.

Using React Router

React Router contains three components:

  • <Router>: The router that holds the user interface up to date with the URL.
  • <link>: This function creates a navigation connection.
  • <Route>: Renders a user interface part based on the URL.

The <ROUTER>

The first step is to decide which router implementation to use.

In Web Apps, you got two options:

We'll use <BrowserRouter>, in index.js, We're going to import this component from react-router-dom and wrap the <App> part in it.

index.js

import React from 'react';
// ...
import { BrowserRouter } from 'react-router-dom';

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

A router part can only have one child feature. A Router component's primary function is to construct a history object that keeps track of the current location (URL). The child component (in this case App>) is re-rendered when the position changes due to a navigation action.

The <Link>

Let's make a navigation menu for our App. open src/App.js and enter the following styles:

import React, { Fragment } from "react";
import "./index.css"

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

export default function App() {
  return (
   <Router>
    <main>
      <nav>
        <ul>
          <li><Link to="/">Home</Link></li>
          <li><Link to="/Messages">Messages</Link></li>
          <li><Link to="/About">About</Link></li>
        </ul>
      </nav>

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

    </main>
</Router>
  );
}

const Home = () => (
  <Fragment>
    <h1>Home</h1>
    <FakeText />
  </Fragment>
  );

const Messages= () => (
  <Fragment>
    <h1>Messages</h1>
    <FakeText />
  </Fragment>
  );

const About = () => (
  <Fragment>
    <h1>About </h1>
    <FakeText />
  </Fragment>
  );

After that, we need to update our navigation bar. Instead of using a tag and href, React Router now uses Connection and to, well, move between sites without having to reload the tab. Then, to swap between pages or elements, we need to add two new paths, About and Touch. We will also use connections to navigate to various areas of our app.

App.js

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

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

By adding these lines we improve it further by wrapping our routes in Switch, which instructs React Router to load just one path at a time.

The <Route>

So far, when a connection is clicked, the URL changes, but the UI does not. Let's change that. For each pathway, we're going to make three components.

Home.js

import React from 'react';

const Home = () => (
  <div>
    <h2>Home</h2>
    My Home page!
  </div>
);

export default Home;

Messages.js

import React from 'react';

const Messages = () => (
  <div>
    <h2>Messages</h2>
    Messages
  </div>
);

export default Messages;

About.js

import React from 'react';

const About = () => (
  <div>
    <h2>About</h2>
    This example shows how to use React Router!
  </div>
);

export default About;

In the browser, you will see:

The most critical term in React Router is routes, and we need to understand them.

Nested Routing

Using children's elements to make anything with a <Route> is the preferred approach. However, there are a couple of other ways to make anything with a <Route>. These are mostly for supporting applications that were created before hooks were added with earlier versions of the router:

  1. component: When the URL matches, the router uses React to generate a React part from the specified component. createElement is a method for creating an element.
  2. render: When the position matches the route's direction, the render prop expects a function to return an element.
  3. children: Similar to Render, Regardless of whether the direction matches the position or not, children are rendered.

Path and Match

The path prop is used to specify which part of the URL should be matched by the router. After that, it would be compared to the same position.

If the router's path and position are successfully matched, an entity called a match object is generated. More detail about the URL and direction can be found in the match object.

The switch Component

As several <Route> are combined, all matching routes are made inclusively. To demonstrate this with an example:

<Route exact path="/"><Home /></Route>
<Route path="/category"><Category /></Route>
<Route path="/products"><Products /></Route>
<Route path="/:id">
  <p>This text will render for any route other than '/'</p>
</Route>

All routes that fit the location /products are made if the URL is /products. As a result, the <Route> function with the path /:id is made alongside the <Products> component. Now that we've learned everything there is to know about the Route and Switch components, let's move on to the next phase.

Security Notice

Any submission for a secure resource on your server must be validated. Since something that runs in the client can be reverse-engineered and tampered with, this is the case.

The client would then submit the JWT as a header for some request for a secured resource, assuming the login was successful. The server will then check this before sending an answer. The server does not store passwords in plaintext when saving them. It will instead encrypt them.

Conclusion

As you have seen in this article, React Router is a fantastic library that allows one to move from a single page to a multi-page program with ease. Long story short, a router keeps UI and the URL in sync.

With the help of this tutorial, You now know how to set up React Router, as well as its most critical components and how routes operate.



About the author:
I like writing content about C/C++, DBMS, Java, Docker, general How-tos, Linux, PHP, Java, Go lang, Cloud, and Web development. I have 10 years of diverse experience in software development. Founder @ Studytonight