TeachingBee

How to use Routing in React JS: A Comprehensive Guide

routing in react js

Introduction

This tutorial about React Js routing we’ll take the review of react-router and see various components of routing in react js. React-router is a particular library to handle routes in an online application. In essence, what React Js Routing does is conditionally render specific components in accordance with the route specified within the URL / for the homepage).

What is the reason to use React Js Routing? It allows you to create single page internet applications (SPA) that have navigation. React Router makes use of component structure to invoke components, that display the relevant information.

React router also permits users to make use of browser functions like the back button and the refresh page while maintaining the original display that the app provides.

Installing React-Router

We’ll use the very popular react-router library for handling different react router links and routing in react js. To use the react-router library, you’ll have to install it with the package manager for NPM:

npm install --save react-router-dom

After installing react-router it will import some applications from libraries and then update our application’s structure. Before we start making those changes allow us to step back and take an overall look and see the reasons for how we build our app in this manner.

Using Routing in App

Conceptually, with React there is possibility of creating the structure of a tree using components and interconnected components. By using the approach of single page application using routes, we can imagine the various parts on a webpage as child.

With a view point of React Js routing within a single page application, we can use the subtree in which we are located and then switch it to another subtree. It is then possible to move to various trees within the browser. In a simpler words we’ll create a React component which acts as the root element of the Routable elements. Then, we can communicate with React to alter the view, and it can simply swap out the entire React component to another as if it’s a different web page being rendered by servers.

Let’s take an App component and specify all of the possible routes we could create in our application in the App component. We’ll have to pull a few parts from the package react-router. The components we’ll need to use to build the structure are:

BrowserRouter / Router

It’s the one that we will utilize to define the root of it’s the route tree. It is the component that React will replace its children on an individual basis.

Route

This component is used to create a react js routing at a particular location via a URL. The component is mounted on URLs on pages that correspond to the specific route that is set up in the configuration props for the route .

An older, but more efficient method to handle client-side navigation is to utilise the number ‘#’ to identify the endpoint of the application. This method is what we’ll employ. We’ll require this object to be loaded to inform the browser that it’s the way we’d like to manage our navigation.

We need to modify our src/App.js to include these modules. We’ll add the BrowserRouter using a different syntax using the ES6 interface:

import React from “react”;
import { BrowserRouter as Router, Route } from “react-router-dom”;

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

export class App extends React.Component {
 render() {
  { /* routes will go here */} ;
 }
}

Let’s first define our initial route. To define a path, we’ll make use of the <Route/> export components from react-router and then pass it several props to:

  1. path – The route for this route is active
  2. component – The part that defines the vision of the route

Let’s define the a route at the root path / with a stateless component that just displays some static content:

const Home = () => 
  <div>
  <h1>Home/h1>
   </div>
 ); 

// ... 

class App extends React.Component { 
  render() { 
  return (
    <Router>
      <Route path="/" component={Home} />
    </Router>
   ); 
 } 
}

Output:

Home

When we load this page into our browser we find our one-way route from the root URL. This isn’t much of an experience. Let’s create a second route that displays an about page on the URL /about.

const Home = () => 
  <div>
  <h1>Home/h1>
   </div>
 );
 // ... 
class App extends React.Component { 
  render() { 
   return ( 
     <Router>
        <div>
          <Route path="/" component={Home} />
          <Route path="/about" component={About} />
        </div>
    </Router>
  ); 
 } 
}

Output:

Home

React Router Links

To permit our users to move freely between two routes we’ll have to include an anchor tag (<a/>). However, the use of tags will inform that the browser to treat the route as if it’s an server-side route. Instead, we’ll have to make use of a different component using link in react router <link/>. It needs prop “to” which indicates the client side route we wish to render.

Let’s change Home and About component so that we use the Link:

import { BrowserRouter as Router, Route, Link } from "react-routerdom"; 
const Home = () => (
  <div>
  <h1>Home</h1>
  <Link to="/about">About Page Link</Link>
  </div> 
); 

const About = () => (
  <div>
   <h1>About</h1>
   <Link to="/">Home Page Link</Link>
  </div>
 ); 

// ...

But this will show up both the routes. This is because the router renders any content that corresponds to the route. In this instance, the react router provides Switch component.

The <Switch/> component only renders the first match route it locates. We’ll update our component to utilise it’s Switch component. Since react router is trying rendering both parts, we’ll have to specify that we require a exact match to the component that is in the root.

import { BrowserRouter as Router, Route, Link, Switch } from "reactrouter-dom"; 
// ... 

const Home = () => 
 <div>
   <h1>Home</h1>
   <Link to="/about">Go to about</Link>
 </div>
);

// ... 

class App extends React.Component { 
render() { 
   <Router>
      <Switch>
        <Route path="/about" component={About} />
        <Route path="/" component={Home} />
      </Switch>
   </Router>
  return ( );
 }
}


Output:

Home

About Page Link

Showing Views

While this is only a brief introduction, we can’t let the discussion about working with react routers without talking about the various ways to enable subcomponents to render.

The render prop is believed as a method which will be called using the match object, along with the route and location configuration. The render prop lets us render anything we like in a sub route. This also includes rendering other routes. What a great idea, right? Let’s take a look at this in practice:

We now have several pages in our app. We’ve examined the ways we could render these routes using interconnected components using just one or two outputs from react-router .

React-router offers a lot more features that we don’t have the time to go through in our short introduction to routing.

const Home = () => (Welcome home Go to about ); const About = ({ name }) => (About {name}); // ... class App extends React.Component { render() { return ( (
   <Router>
      <Switch>
        <Route path="/about" render={
        renderProps => (
           <div>
              <Link to="/about/ari">Ari</Link>
              <Link to="/about/nate">Nate</Link>
        
        <Route path="/about/:name" render={renderProps => (
        <div>
          <About name={renderProps.match.params.name} />
          <Link to="/">Go home</Link>
        </div>
       )}
       />
        </div>
    )}
    />
       <Route path="/" render={
          renderProps => (
            <div> Home is underneath me <Home {...this.props} {...renderProps} />
         </div>
      )}
    />
    </Switch>
    </Router>
   );
  }
}

Conclusion

It’s incredibly simple to incorporate React Js Routing into your applications. It helps to make the UI more attractive and lively. It is important to define the correct routing in react js, react router links and all the components of the route component in order to make it function properly. Before you implement the strategies you must have a fundamental understanding of the component as well as the hierarchy of react components is required. There could be modifications to or in the API and in version, so it is best to refer to the official documentation to learn about the application.

Got a question or just want to chat? Comment below or drop by our forums, where a bunch of the friendliest people you’ll ever run into will be happy to help you out!

90% of Tech Recruiters Judge This In Seconds! 👩‍💻🔍

Don’t let your resume be the weak link. Discover how to make a strong first impression with our free technical resume review!

Related Articles

angular js vs React

Angular JS vs React: Which is Better?

Introduction JavaScript is a client-side scripting language used to provide dynamic attributes as well as features to HTML web pages . JavaScript was created to assist the browser by enabling

Why Aren’t You Getting Interview Calls? 📞❌

It might just be your resume. Let us pinpoint the problem for free and supercharge your job search. 

Newsletter

Don’t miss out! Subscribe now

Log In