Using React Router in your React app

Using React Router in your React app

ยท

3 min read

What is an SPA?

A single-page application (SPA) is a website that re-renders its content in response to navigation actions (e.g. clicking a link) without making a request to the server to fetch new HTML.

Why react uses React Router?

In general, when the user types a URL in the browser, an HTTP request is sent to the server, which then retrieves the HTML page. For each new URL, the user is redirected to a new HTML page.

noRouter.e4e96b24.png

However, when using React router, the request does not go all the way to the server, instead the React Router intercepts the requests and what React router does is that it recognizes the component that we want to render, based on that it injects that particular component into the DOM.

reactRouter.5b0f0fbf.png

Installation and Setup

To use React Router, you first have to install it using NPM:

npm install react-router-dom

You'll need to import BrowserRouter, Route, and Switch from react-router-dom package:

import React, {Component} from 'react';
import {(BrowserRouter, Route, Switch)} from 'react-router-dom';

First, you'll need to set up your app to work with React Router. Everything that gets rendered will need to go inside the BrowserRouter element, so wrap your App in those first.

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

Next, in our App component, add the Switch element .These ensure that only one component is rendered at a time. The Switch component will only render the first route that matches/includes the path.

//app.js
function App() {
      return (
        <div>
            <Switch>

            </Switch>
         </div>)
  }

It's now time to add your Route tags. These are the links between the components and should be placed inside the Switch tags.

To tell the Route tags which component to load, simply add a path attribute and the name of the component you want to load with component attribute.

<Route path='/' component={Home} />

Many homepage URLs are the site name followed by "/". In this case, we add exact to the Route tag. This is because the other URLs also contain "/", so if we don't tell the app that it needs to look for just "/", it loads the first one to match the route, and we get a pretty tricky bug to deal with.

//app.js
function App() {
{
return (
     <main>
        <Switch>
          <Route path="/" component={Home} exact />
          <Route path="/about" component={About} />
          <Route path="/footer" component={Footer} />
        </Switch>
     </main>
   }
  )
}

Now import Home, About and Footer components in your app

import Home from './Home';
import About from './About';
import Footer from './Footer';

Also provide an appropriate error message, which loads if a user types an incorrect URL. This is just like a normal Route tag, but with no path.

<Route render = { () => <h4> DANGGG. Error 404 </h4> } />

So far, our site is only navigable by typing the URLs. To add clickable links to the site, we use the element from React Router and set up a new Navbar component. Once again, don't forget to import the Navbar component into the app.

//navbar.js
function Navbar() {
       return (
          <div>
             <Link to="/">Home </Link>
             <Link to="/about">About Me </Link>
             <Link to="/footer">Footer </Link>
          </div>
     );
  };

Woohoo!๐Ÿฅณ Your site now has clickable links that can navigate you around your SPA!

Conclusion

If you want to easily navigate around a React app, forget the anchor tags and add React Router. It's clean, organized, and it makes adding and deleting pages a whole lot easier.

Thanks for reading this.๐Ÿ™๐Ÿป

If you'd like to read more such articles, check out my medium profile.

Check out my personal blog .