The Amazing React Router

Written by SELMAe33 | Published 2020/08/30
Tech Story Tags: react | react-router | javascript | web-development | front-end-development | frontend | node-http-request-router | software-engineering | web-monetization

TLDR React-Router is the ability to move between different parts of an application when a user enters a URL or clicks an element (link, button, icon, image, etc) within the application. In single-page apps, there is only a single HTML page to render the different components based on the navigation of the page. To see the routes in action, we will edit the App.js and then create other components. We will then import the React router on our index.js.via the TL;DR App

Context
Usually, when you load up a website, most of the pages like the about page, the contact page have to fetch data from the server before rendering. With React, and React Router, everything becomes simplified because only a specific component loads up. In single-page apps, there is only a single HTML page. we are reusing the same HTML page to render the different components based on the navigation.

What exactly is Routing?

Routing is the ability to move between different parts of an application when a user enters a URL or clicks an element (link, button, icon, image, etc) within the application.

Using Routers in a React App

In order to understand exactly how routes work in react, we will need to create a react app. Create a react app by typing the command below
npx create-react-app routing
By default, when you use the above command to create a react app, it creates other files and folders, two of which are the App.js, and the Index.js. The App.js acts like the main component that renders all other components. The Index.js then renders the App.js.
At this point, installing the react-router package is easy. Navigate into the react app and install the react-router package.

Installing the React Router

Assuming that react has already been installed and the react app created, we can go ahead and install the react-router. To extend your application by adding routing capabilities, you will use the popular React-Router library. It’s worth noting that this library has three variants:
  • react-router: the core library
  • react-router-dom: a variant of the core library meant to be used for web applications
  • react-router-native: a variant of the core library used with react native in the development of Android and iOS applications.
Because our scope is web applications, we are most interested in the react-router-dom which imports all the functionality of the core react-router library. To install react-router-dom, navigate to the root folder of the project and type the following command
npm install react-router-dom
To see the routes in action, we will edit the App.js and then create other components.
// App.js

import React from 'react'

class App extends React.Component {
  render() {
    return (
      <div>
        <h1>Home</h1>
      </div>
    )
  }
}
export default App
//contact.js

import React from 'react'

class Contact extends React.Component {
  render() {
    return <h1>Contact</h1>
  }
}
export default Contact
//About.js

import React from 'react'

class About extends React.Component {
  render() {
    return <h1>About Us</h1>
  }
}
export default About
Now our app has three components one is App and the other two are About and Contact.

Routing

In the Index.js, we will import the react-router-dom package we installed earlier, then we will import all the other components as follows;
//index.js

import React from 'react'
import ReactDOM from 'react-dom'
import { Route, Link, BrowserRouter as Router } from 'react-router-dom'
import './index.css'
import App from './App'
import About from './About'
import Contact from './contact'
Notice that the react-router package includes a number of routers that we can take advantage of depending on the platform we are targeting. These include BrowserRouter, Route, Link.
BrowserRouter
The BrowserRouter is used for applications that have a dynamic server that knows how to handle any type of URL.
Route
The <Route/> component is one of the most important building blocks in the React Router package. It renders the appropriate user interface when the current location matches the route’s path. The path is a prop on the <Route/> component that describes the pathname that the route should match.
Link
The react-router package also contains a <Link/> component that is used to navigate the different parts of an application by way of hyperlinks. It is similar to HTML’s anchor element but the main difference is that using the Link component does not reload the page but rather, changes the UI.
Using an anchor tag would require that the page is reloaded in order to load the new UI. When the Link component is clicked, it also updates the URL.as shown in the example that follows
Combining the above knowledge on BrowserRouter, Route, and Link, we can update our index.js to look like this
//index.js

import React from 'react'
import ReactDOM from 'react-dom'
import './index.css'
import { Route, Link, BrowserRouter as Router } from 'react-router-dom'
import App from './App'
import About from './about'
import Contact from './contact'

const routing = (
  <Router>
    <div>
      <ul>
        <li>
          <Link to="/">Home</Link>
        </li>
        <li>
          <Link to="/about">About</Link>
        </li>
        <li>
          <Link to="/contact">Contact</Link>
        </li>
      </ul>
      <Route exact path="/" component={App} />
      <Route path="/about" component={About} />
      <Route path="/contact" component={Contact} />
    </div>
  </Router>
)
ReactDOM.render(routing, document.getElementById('root'))
After adding navigation you will see the routes are rendered on the screen. if you click on any of the routes you will see that the URL is changing and the individual component is rendered.
What if the user types a URL that is not found on the web page?
The best way to handle these cases is to create a not-found component or what is usually called 404 pages.

What is a 404 Page?

A 404 page is also called a "not found" page. This happens when a user navigates to the wrong path that doesn’t exist on the website. To be able to redirect to a 404 page, we need to import another react-router package router called Switch.

Switch

Switch component helps us to render components only when the path matches, otherwise it fallbacks to the not found component.
Let's demonstrate this by creating a not-found component;
//notfound.js

import React from 'react'

const Notfound = () => <h1>Not found</h1>

export default Notfound
We then import the Switch router on our index.js as shown below
//index.js

import React from 'react'
import ReactDOM from 'react-dom'
import './index.css'
import { Route, Link, BrowserRouter as Router, Switch } from 'react-router-dom'
import App from './App'
import About from './about'
import Contact from './contact'
import Notfound from './notfound'
const routing = (
  <Router>
    <div>
      <ul>
        <li>
          <Link to="/">Home</Link>
        </li>
        <li>
          <Link to="/about">About</Link>
        </li>
        <li>
          <Link to="/contact">Contact</Link>
        </li>
      </ul>
      <Switch>
        <Route exact path="/" component={App} />
        <Route path="/about" component={About} />
        <Route path="/contact" component={Contact} />
        <Route component={Notfound} />
      </Switch>
    </div>
  </Router>
)
ReactDOM.render(routing, document.getElementById('root'))
Notice how the Notfound component has no path specification. Each time a user enters a wrong path, or any path not specified in the index.js, that user will be redirected to the 404 pages or the not-found page.
Leave a like if this article was helpful to you

Written by SELMAe33 | Full Stack Developer
Published by HackerNoon on 2020/08/30