Routing using React Router.

Photo by Andrew Neel on Unsplash

Routing using React Router.

A beginner friendly tutorial on React Router.

React is a common javascript library that makes javascript easy to use, one of the reasons why react is awesome is React Router. In this tutorial, we will be discussing: what is React Router and how to set it up on your local machine. Then as you progress, you will learn about some of the features of React Router and how to use them to navigate to different routes and render multiple components.

Let's look at page rendering in React to have a good overview of why React Router is important.

Page rendering in react

React renders pages on a website in the form of a Single Page Application (SPA) i.e. the website seems like a single HTML file displayed on the server. If you stick to this concept of SPA, creating multiple-page websites would seem impossible and that is where React Router comes to the rescue.

Routing is a technique used to navigate between web pages based on the user's actions or requests on the website. The React Router is a library that makes routing possible by defining different routes and displaying the contents assigned to each route.

In non-single-page applications, when you click on a link in the browser, a request is sent to the server and then the page is displayed on the browser; however, in React the React Router intercepts the request being sent to the server and then displays the content of the components we have created.

When you create a new React project, the contents displayed on the browser are the content of the index.html file and the App component acts as the root, but what happens if you have multiple pages in our project? the first solution will be to create multiple html files for the different pages, but since we are dealing with SPAs the React Router will work in such a way that, as you navigate to different routes, the content of the index.html file will be re-written to the content of the components assigned to the current Route we're in i.e as you change the Route the contents displayed on the browser will change according to the logic of the components assigned to that Route. Now let's see how you can use React Router in your project.

Prerequisites

To follow up and have a good understanding of the concepts explained in this tutorial, you need a basic understanding of the following:

  • A good understanding of react components

  • How to use Command Line Interface (CLI)

  • Node.js installed on your machine

  • A react app

How to Install React Router

To install React Router you need to have Node.js already installed on your machine. If you don't have it on your machine yet, you can download it here: Node.js

Once you have installed Node.js on your machine type in: - node -v in your command prompt, it should give you a version number if you have installed it successfully- then to install React Router, you need to install react-router-dom which is a specialized package for React and it contains React Router. To install react-router-dom do the following:

  1. Open the terminal on your code editor.

  2. Navigate to your project directory.

  3. Type in : npm install react-router-dom@6.4 (6.4 is the version number)

After react-router-dom has been installed you will find it in your package.json file.

Setting Up React Router

Now that you have installed react-router-dom, to use React Router you have to make it available anywhere you need it by using the import statement. The App component is the root element in our React project so let's set up our React Router in our App.js file. In this tutorial, we will consider a website that has the Home,Contact and About page and in our React project each of these pages has its Component. From react-router-dom version 6.4, there is a new way to work with react-router-dom; however, this tutorial will cover the previous way and the new way to work with version 6.4 and above. Let's start with the previous way. In any file in our React project, you will import the features of react-router-dom you need in that file. The App.js file will look like this:

import {BrowserRouter,Routes,Route,Link} from "react-router-dom"
import Home from "./Home"
import About from "./About"
import Contact from "./Contact"
function App(){
return(
<BrowserRouter>
<div className="App">
<Routes>
<Route path="/" element={<Home/>}/>
<Route path="about" element={<About/>}/>
<Route path="contact" element={<Contact/>}/>
</Routes>

</div>

</BrowserRouter>
);

}

export default App;

From the first line of code, we imported the Components needed from react-router-dom which are:

  • BrowserRouter-this component wraps the whole application so we can use the Router.

  • Routes-this acts as a parent component to the multiple Route within it.

  • Route- this component has the path prop and element prop.

If we look at the Route component, the path prop defines the URL path and the element prop assigns the Component the route will render. In the home Route you use the "/" since it is the root path so we can use "/" only.

Multiple Components Assigned to each Route

You have to create the Home,About and Contact components for our project will look like this:

Home Component:

export default function Home(){
   return(
<div>
<h2>
This is the home page
</h2>
</div>

)
}

About Component:

export default function About(){
   return(
<div>
<h2>
This is the About page
</h2>
</div>

)
}

Contact Component:

export default function Contact(){
   return(
<div>
<h2>
This is the Contact page
</h2>
</div>

)
}

We stated earlier in this tutorial that the react-router-dom version 6.4 has a new way to set it up and also some new features so let's consider that now. The App.js file will now look like this:

import {createBrowserRouter,createRoutesFromElements,RouterProvider,Routes,Route,Link} from "react-router-dom"
import Home from "./Home"
import About from "./About"
import Contact from "./Contact"

const myrouter=createBrowserRouter(
createRoutesFromElements(
<Route path="/" element={<Layout/>}>
<Route index element={<Home/>}/>//"index" can be used for the first path
<Route path="about" element={<About/>}/>
<Route path="contact" element={<Contact/>}/>
</Route>
)
)

function App(){
return(
<div className="App">
<RouterProvider router={myrouter}/>
</div>
);
}

export default App;

You can see that this current way being considered is a bit different from the one that was explained previously, so let's break it down:

  • You created a variable called myrouter and we use the createBrowserRouter and createRoutesFromElement to define the routes.

  • If you are to use this new method then you have to use the "Route" and not "Routes" component as the parent component to wrap the multiple Route within it.

  • You have the Layout component in the parent Route that wraps the other multiple Route

    In the RouterProvider component we pass the myrouter variable as a router prop.

In this new method of setting up react-router-dom, if you have some links to some other pages within the website. You have to use the Outlet component which will tell React Router where to render the content of the page in which the link was clicked. The Layout.js file will look like this:

import {Navlink,Outlet} from "react-router-dom"

export default function Layout(){
return (
<div>
<nav>
<h1>This is a website</h1>
<Navlink to="/">Home</Navlink>
<Navlink to="about">About</Navlink>
<Navlink to="contact">Contact</Navlink>
</nav>
<main>
<Outlet/>
</main>
</div>
)
}

When you click on any of the links, the content of the page will be rendered where you have the Outlet component.

How to Navigate to Different Routes

In React Router, you can use Link and Navlink component to navigate through the website. Let's look at the Layout.js file above one more time:

import {Navlink,Outlet} from "react-router-dom"

export default function Layout(){
return (
<div>
<nav>
<h1>This is a website</h1>
<Navlink to="/">Home</Navlink>
<Navlink to="about">About</Navlink>
<Navlink to="contact">Contact</Navlink>
</nav>
<main>
<Outlet/>
</main>
</div>
)
}

If you replace the Navlink with the Link component, the code will look like this:

import {Link,Outlet} from "react-router-dom"

export default function Layout(){
return (
<div>
<nav>
<h1>This is a website</h1>
<Link to="/">Home</Link>
<Link to="about">About</Link>
<Link to="contact">Contact</Link>
</nav>
<main>
<Outlet/>
</main>
</div>
)
}

One of the advantages of Navlink over Link is that Navlink has an active class, which you can use to style the links on your page for hover effects and some other nice styles, for example:

a .active:hover{
background-color: red;
color: white;
border: 2px solid brown;
}

The code above will only work when you use the Navlink component for links on our page because it is the component that has the active class

On the website, when you click on any link it will change the URL path of the page to the route assigned to the link.

Custom Error page

By default, React Router has an error page if you try to go to an undefined Route within the website or another form of error occurs. You can also create a custom error page for our website. Let's take a look:

import {createBrowserRouter,createRoutesFromElements,RouterProvider,Routes,Route,Link} from "react-router-dom"
import Home from "./Home"
import About from "./About"
import Contact from "./Contact"
import Notfound from "./Notfound"
const myrouter=createBrowserRouter(
createRoutesFromElements(
<Route path="/" element={<Layout/>}>
<Route index element={<Home/>}/>
<Route path="about" element={<About/>}/>
<Route path="contact" element={<Contact/>}/>
<Route path="*" element={<Notfound/>}/>
</Route>
)
)
//"index" can be used for the first path
function App(){
return(
<div className="App">
<RouterProvider router={myrouter}/>
</div>
);
}

export default App;

The path assigned for the error page is represented by "*", so we now have to create the Notfound component(we can use any name). The Notfound.js file will look like this:

import { Link } from "react-router-dom";

const Notfound = () => {
    return ( 
        <div className="not-found">
            <h2>Sorry, this page cannot be found</h2>
            <br />
            <Link to='/'>Back to Homepage...</Link>
        </div>
     );
}

export default Notfound;

Conclusion

Congratulations on getting to this point in the tutorial. You have now seen how to install, set up and use some basic features of the React Router. This is a good foundation to get started with React Router, but there are some more interesting features we didn't discuss here like Nested Routes, Loader functions etc. You can check out this documentation for more insights: React Router docs

"Genkai wo Koero" - Surpass Your Limits.