DEV Community

Cover image for A Quick Guide to Understanding React Router
Victory Tuduo
Victory Tuduo

Posted on • Originally published at hashnode.com

A Quick Guide to Understanding React Router

Why react router?

When building single page applications on the web with multiple views it is a better practice to use display different pages using router and help your user navigate through them rather than having to refresh the whole web page every time your user switches between pages.
Here we’ll go over a React library for routing between pages: The React Router.

Prerequisites

To be able to fully grasp this tutorial it is expected you have:

  1. Basic knowledge of JavaScript, Reactjs and React Hooks.
  2. You have a version of Node.js installed.
  3. Access to Package managers such as npm/yarn/npx.

Getting Started

STEP 1: Install React Router
First step to using React Router will be installing the appropriate package.
There are basically three (3) different packages: React Router, React Router DOM and React Router Native.
The React Router is the core dependency use for the other two packages listed above. React Router DOM is for building web applications while React Router Native is for mobile applications built with React Native.
We install React Router DOM from our command line by writing:

using npm

npm install react-router-dom
Enter fullscreen mode Exit fullscreen mode

using yarn

yarn add react-router-dom 
Enter fullscreen mode Exit fullscreen mode

SETTING UP REACT ROUTER

After installation is complete we need to set up the router for use within our react project. We do this with a component called BrowserRouter. Browser Router keeps track of routes history in the react app.To import we write:

Import {BrowserRouter, Route} from ‘react-router-dom’;
Enter fullscreen mode Exit fullscreen mode

Note that its also a practice to add an alias as Router when importing the BrowserRouter. It can be written as:

Import {BrowserRouter as Router, Route} from ‘react-router-dom’;
Enter fullscreen mode Exit fullscreen mode

To provide routes within our application we import the Route component and then wrap our application within routes:

function App(){
        return (
            <Router>
            {/* routes go in here*/}
            </Router/>
            );
}
export default App;
Enter fullscreen mode Exit fullscreen mode

This way we declare individual routes within our application.
You cannot access any router specific data that is declared outside the router. To do that we use history data.

USING THE ROUTE COMPONENT

To use the routes we declare them with two props for every route: path and component.

function About() {
  return (
    <div>
      <p>this is an about page.</p>
    </div>
  );
}
export default About;

Enter fullscreen mode Exit fullscreen mode

We can then import this into our App and use a route:

function App() {
  return (
    <Router>
      <Route path="/about" component={About} />
    </Router>
  );
}
Enter fullscreen mode Exit fullscreen mode

The path props tells us what path our route is located.
The component prop contains the component for the declared path. Numerous routes can be declared within the router. Alternatively we can also write a route without the component prop:

<Router>
      <Route path="/about">
        <About />
      </Route>
    </Router>
Enter fullscreen mode Exit fullscreen mode

You can display a component in every of the routes by adding the component within the Router:

function App() {
  return (
    <Router>
      <Contact />
      <Route path="/Home" component={Home} />
        <Route path="/about" component={About} />
    </Router>
  );
}

function Contact() {
  // visible on every page
  return <>This is a contact</>
}
Enter fullscreen mode Exit fullscreen mode

At this point we notice that when we have more than one route within our router we see all the contents for all the routes when we visit each route component
We solve this using the Switch Component:

import { BrowserRouter, Switch, Route } from "react-router-dom";
Enter fullscreen mode Exit fullscreen mode

We then wrap our Routes within the Switch:

<Router>
      <Contact />
      <Switch>
        <Route exact path="/" component={Home} />
        <Route path="/about" component={About} />
      </Switch>
    </Router>
Enter fullscreen mode Exit fullscreen mode

The Switch component is used to check the child routes and display only the one which the URL matches the current path.

CREATING NAVIGATION

We can navigate through our routes with the help of a Link component:

import { BrowserRouter, Routes, Route, Link } from 'react-router-dom';
Enter fullscreen mode Exit fullscreen mode

We then write the Link with a prop To which contains the path to the component to be rendered:

<Link to=”/about”>
  //here we can add an item link an anchor tag, button or nav item to perform navigation on click
</Link>
Enter fullscreen mode Exit fullscreen mode

PAGE NOT FOUND (404)

Using routes we can also create a custom 404 page in the event that a user navigates to a path that doesn’t exist within the application. To do that we create a Route with a path of *:

//other code as before  
<Route path="*" component={NotFound} />
Enter fullscreen mode Exit fullscreen mode

Any time the user navigates to a path that does not exist they will be navigated to the NotFound component.

USE HISTORY HOOK

React Router DOM provides us with a component called use History which allows us to return information associated with our component such as the path associated with our current component.

import { useHistory } from "react-router-dom";
function About() {
  const history = useHistory();

  console.log(history.location.pathname); // will return '/about'

  return (
    <>
     <h1>current path: {history.location.pathname}</h1>
    </>
  );
}
Enter fullscreen mode Exit fullscreen mode

PASSING DATA BETWEEN ROUTES

We can pass a value from one page to another page routed to within our path by adding it within our Route by adding it as a parameter:

 <Route path = "/Result/:id" component={Result} />
Enter fullscreen mode Exit fullscreen mode

If we wish to pass a variable such as an item name from within the Result Component referenced above we can add it within our Link.

<Link to={`/Result/${thevaraible}`}
Enter fullscreen mode Exit fullscreen mode

We can then access the information from the path on the routed page from the link by referencing it as a params:

const Results =({match : { params }) =>{
    return( <h1>{params.id}</h1>)
}
Enter fullscreen mode Exit fullscreen mode

CONCLUSION

The purpose of this blog was to give you a quick insight on how to implement React router for use within your React app. With this you should be able to make use of the react router DOM to build web applications.

Top comments (0)