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

The Complete Guide to Routing React Apps
1 Likes15.15 GEEK