Getting started with React Router

Getting started with React Router

React router is a routing library built on top of the react which is used to create the routing in react apps.

Introduction

One of the simple definition of routing is navigation between pages. Routing is provided by many JavaScript frameworks especially React. React is a JavaScript library for building user interfaces.

Introducing Routing in React

React provides several libraries for routing. React community provides several routing solutions available here. Let’s take a look at the React routing libraries download statistics over time:

Compare npm package download statistics over time: aviator vs component-router vs director vs finch vs react-router vs router5

React Router is the popular routing library for React.

Introducing React Router

Built and maintained by React Training team, React Router is a powerful routing library. React Router 4 is the latest version and was divided into four packages:

  • react-router: the core of React Router;
  • react-router-dom: the dom version designed for browsers or web apps;
  • react-router-native: the native version designed for react-native mobile apps;
  • react-router-config: all static route configuration helpers.

    What you’ll learn

You’re here to learn about routing in <a href="https://www.dunebook.com/react-examples-best-websites-built-using-react/" target="_blank">React</a> applications, and, in this post, we are going to cover the basics of Routing in React applications. The methods of routing we will explore are:

  • Basic Routing
  • Nested Routes
  • URL Parameters
  • 404 Pages
  • Redirects (Authentication)

Let’s create a simple app to illustrate React Router basics.

We will be using a lot of components which is part of a sample application to explain routing. Take a look at this app:

Where does that come from? 😄

npx create-react-app remote-tools-app
cd remote-tools-app
npm install --save bootstrap
npm install react-router-dom

We installed bootstrap package to make the app look pretty and react-router-dom package. I do not display the complete source code of the files but only the important parts for the understanding of this article. You can access the source code at the end of this article.

The first thing to do is to import BrowserRouter for browser-based projects. Just surround your app with that component. So your app is ready to use React Router.

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

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

One of the elements that allow us to navigate between pages remains the links. React Router allows you to create components to navigate between pages. For example,

<Link to="/"> Remote tools </Link>

The <Link> component has an attribute called to which is similar to the href attribute.

Once a link is created in your application, it is important to match a link with a React component. Say hello to <Route> component:

<Header />
  <Switch>
    <Route exact path="/" component={Home} />
  <Switch/>
<Footer />

You can simply read the code above like this: switch the <Home> component between Header and Footer components when the path is /. What would become something like below:

<Header /> 
  <Home></Home>
<Footer />

Otherwise, we would have:

<Header /> 
<Footer />

Do you know when we have the case above? When a path does not exist for example (remember page not found errors).

You can handle those cases with React Router too.

<Header /> 
  <Switch> 
    <Route exact path="/" component={Home} /> 
    <Route component={NotFound} /> </Switch>
<Footer />

If the path “/” match display Home component. If not, display <NotFound> component.

When creating applications, you often need to add restrictions: authorization, authentication, etc. For example, you want to prevent <Collection> component from being displayed only for logged users. React Router allows you to create a <PrivateRoute> component:

<Header /> 
  <Switch> 
    <Route exact path="/" component={Home} /> 
    <Route path="/login" component={Login} />
    <PrivateRoute authed={false} path="/collections" component={Collection} /> </Switch>
    <Route component={NotFound} /> 
  </Switch>
<Footer />

React Router lets you create a <PrivateRoute> component. Let’s look at this below:

import React from 'react'
import {
  Route,
  Redirect
} from 'react-router-dom'

function PrivateRoute({component: Component, authed, ...rest}) {
  return (
    <Route
      {...rest}
      render={(props) => authed === true
        ? <Component {...props} />
        : <Redirect to="/login" />
      }
  )
}
export default PrivateRoute 

Simple. It is a component that returns a <Route> component based on parameters, including the authed attribute. We use <Redirect> component which allows a redirection if the condition is not fulfilled.

If you want to see if the route is protected, change the authed parameter from false to true and see the result.

At this point, our app is about almost done. We still need to add nested routes.

<Header /> 
  <Switch> 
    <Route exact path="/" component={Home} />
    <Route path="/login" component={Login} />
    <Route path="/products/:product" component={Product} />
    <PrivateRoute authed={false} path="/collections" component={Collection} /> </Switch>
    <Route component={NotFound} /> 
  </Switch>
<Footer />

It’s a <Route> component again with a path (/products/:product) and a component (Product). And you can access this parameter like below:

const Product = ({ match }) => {
  console.log(match.params.product) 
} 

Congrats! You can now play with routing in React apps. The full codebase is on Github.

reactjs javascript

What's new in Bootstrap 5 and when Bootstrap 5 release date?

How to Build Progressive Web Apps (PWA) using Angular 9

What is new features in Javascript ES2020 ECMAScript 2020

Deno Crash Course: Explore Deno and Create a full REST API with Deno

How to Build a Real-time Chat App with Deno and WebSockets

Convert HTML to Markdown Online

HTML entity encoder decoder Online

Random Password Generator Online

HTML Color Picker online | HEX Color Picker | RGB Color Picker

The essential JavaScript concepts that you should understand

The essential JavaScript concepts that you should understand - For successful developing and to pass a work interview

JavaScript Expressions in JSX in ReactJs

Welcome, what is JSX Expressions in React Js in Hindi? JSX is an Expression Too After compilation, JSX expressions become regular JavaScript function calls a...

Grokking Call(), Apply() and Bind() Methods in JavaScript

In this article, we will have a look at the call(), apply() and bind() methods of JavaScript. Basically these 3 methods are used to control the invocation of the function.

ReactJS vs Angular vs Vue: Best Javascript Framework For Your Project

ReactJS vs Angular vs Vue: Best Javascript Framework For Your Project. This video covers the key differences between ReactJS, Angular and Vue with respect to the following: Use case, Performance, Data binding, Scripting language, Testing, Community support, Growth curve

What is JavaScript – All You Need To Know About JavaScript

In this article on what is JavaScript, we will learn the basic concepts of JavaScript.