The Complete Guide to Routing React Apps

The Complete Guide to Routing React Apps

Routing being a key aspect of web applications (and even other platforms) could not be left out in React...

Routing being a key aspect of web applications (and even other platforms) could not be left out in React...

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

MarkupCopy

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'));

JsCopy

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 />

JsCopy

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 />

JsCopy

Otherwise, we would have:

<Header /> 
<Footer />

JsCopy

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 />

JsCopy

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 />

JsCopy

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 

JsCopy

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 />

JsCopy

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) 
} 

JsCopy

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

reactjs

Bootstrap 5 Complete Course with Examples

Bootstrap 5 Tutorial - Bootstrap 5 Crash Course for Beginners

Nest.JS Tutorial for Beginners

Hello Vue 3: A First Look at Vue 3 and the Composition API

Building a simple Applications with Vue 3

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

Why ReactJS is better for Web Application Development?

Web Application Development is the point of contact for a business in today's digital era. It is important to choose the right platform for Web Application Development to build a high end Web

ReactJs Course | How to build a YouTube Clone using ReactJS

Hello, this is a new tutorial series about ReactJs. In this series, I will teach you two important topics. First, I will be teaching you what is ReactJs library and why this is so powerful and expandable. We will see what are the important...

Top Reasons to Choose ReactJS for Front-End Development - Prismetric

Why ReactJS is perfect choice for your next web application? Get to know all about ReactJS development and its benefits in detail for frontend development.

ReactJS Web App Development Services

We provide top-notch ReactJS development services to global clients. Hire expert ReactJS developers from top React JS development company, Skenix Infotech.

Highcharts with Reactjs

#reactjs #highcharts #therichpost https://therichpost.com/highcharts-with-reactjs-working-tutorial/ Highcharts with Reactjs Please like, share and subscribe....