How to use React Router v6 in a React-TypeScript application

Build a “portfolio” website with React and TypeScript

How to use React Router v6 in a React-TypeScript application

Photo by Webstacks on Unsplash

Introduction

React Router is a widely used, popular routing library in React applications. The version 6 (v6) of React Router was recently released which has gone through some fundamental changes compared to the previous versions making it even easier to use. For instance, the new version is about 60% lighter than the previous versions and some changes in component names which are talked about in upcoming lines.

In this project we are going to have an introduction to the fundamentals of React Router v6 by building a “portfolio” website.

The focus of this article is React Router v6 and introducing its most commonly used components , therefore, creating and styling the pages will not be covered in depth. However, the source code is publicly available in my Github. Click here to get access to the source code.

While building a “Portfolio” web app the following will be covered:

  • Configuring Routes and,
  • Navigating with Link

For creating this application we are going to use create-react-app with TypeScript template. The reason for using TypeScript as said in its documentation is that “it can highlight unexpected behavior in your code, lowering the chance of bugs” therefore makes debugging easier for us.

Creating the react app

Go to your working directory and create a react app with a TypeScript template:

npx create-react-app <your-app-name> --template typescript

Our app is called react-router-vsix-app, change directory to the app’s folder, open your code editor (I am using VSCode) and remove the files which are not being used in the application such as logo, favicon and test files. Go to your App.tsx and remove all the code inside the return section. Your App.tsx should look like this at this stage:

import React from "react";
import "./App.css";

function App() {
  return (
    <div className="App"></div>
  );
}
export default App;

Create pages and components

Create three folders inside the src folder: components, pages and img. Create NavBar.tsx and Footer.tsx inside the components folder and Home.tsx, About.tsx, Portfolio.tsx and Contact.tsx inside the pages folder.

Install the react-router-dom

npm install react-router-dom@6

In App.tsx wrap all the components inside the <BrowserRouter> component. <BrowserRouter> is a parent component and is used to store all the other components. It connects the app to the URL by using HTML5 History API so the User Interface (UI) stays in sync with the URL.

In version 6 of react router <Switch> is deprecated and is not exported from react-router-dom. So we do not need to wrap a specific route by <Switch>. However, we use <Routes> instead. Routes wrap <Route> which takes a prop called element where we pass our components to.

Moreover, we do not need to use the exact prop anymore. The new algorithm enables us to match a specific route without using the exact prop. All these changes make the version 6 of React-Router-dom very easy to use.

Import <BrowserRouter>, <Routes> and <Route> from react-router dom on the top of your App.tsx file.

Define routes to each page:

import React from "react";
import { BrowserRouter, Routes, Route } from "react-router-dom";
import "./App.css";
import { About } from "./pages/About";
import { Contact } from "./pages/Contact";
import { Home } from "./pages/Home";
import { Portfolio } from "./pages/Portfolio";

function App() {
  return (
    <div className="App">
      <BrowserRouter>
        <NavBar />

        <Routes>
          <Route path="/" element={<Home />} />
          <Route path="/about" element={<About />} />
          <Route path="/portfolio" element={<Portfolio />} />
          <Route path="/contact" element={<Contact />} />
        </Routes>
        <Footer />
      </BrowserRouter>
    </div>
  );
}

export default App;

Create the Navbar

In this project react-bootstrap is used to style and create components. Feel free to code the Navbar from scratch or use any other frameworks and libraries. Install react-bootstrap if decided to use it in your application:

npm install react-bootstrap bootstrap

Import <Navbar>, <Container> and <Nav> from react-bootstrap and <Link> from react-router-dom on top of your NavBar.tsx file. <Link> enables us to navigate between the pages by using the prop to.

To make the Navbar responsive we need to collapse it on small displays and toggle it back to the original state on larger ones. For this we will use <Navbar.Toggle> and <Navbar.Collapse> from react-bootstrap. Wrap the navigation links inside the <Nav> component.

import React from "react";
import { Navbar, Container, Nav } from "react-bootstrap";
import { Link } from "react-router-dom";

export const NavBar = () => {
  return (
    <Navbar sticky="top"  expand="md">
      <Container>
        <Navbar.Toggle aria-controls="responsive-navbar-nav" />
        <Navbar.Collapse id="responsive-navbar-nav">
          <Nav>
            <Link to="/">Home</Link>
            <Link to="/about">About</Link>
            <Link to="/portfolio">Portfolio</Link>
            <Link to="/contact">Contact</Link>
          </Nav>
        </Navbar.Collapse>
      </Container>
    </Navbar>
  );
};

The useNavigation Hook

There are two react router interfaces being used to navigate between pages:

  1. <Link> and < NavLink > which render <a> elements.
  2. useNavigate and <Navigate> which replace the current location or change the state.

useNavigate replaces useHistory from the previous version of React Router and is being used to handle events. For example when we want to navigate back and forward between pages.

A back link is added to each page so the user can navigate to the previous page through a click event. To do this first import useNavigate and save it into a variable which is going to be used later in handling the click event. The minus number shows that we want to go back to the previous page (-1):

let navigate = useNavigate();
const handleBack = () => {
navigate(-1);
};

Now we can call our navigation handler function which we defined above in our <Button> components:

<Button onClick={handleBack} variant="link">Back</Button>

Adding content and styling

As stated above the main focus of this tutorial was introducing the version 6 of react-router-dom and its usage with React and TypeScript. If interested in the content and styling the app the way I did, check out the source code in my GitHub . Feel free to use this template to build your portfolios.

home.png

This article was originally published on Medium.

I would love to see your portfolios, send me a message with a link to your websites either here or to my Twitter account.

Did you find this article valuable?

Support Sevinu's Blog by becoming a sponsor. Any amount is appreciated!