A picture of a map, a React logo, and a CopyCat logo.

The Most Complete Guide for React Navigation

December 9, 2021
Harita Ravindranath
React.js Navigation

The Fastest Way to Build React UI

Convert Figma designs to production-ready React.js code. Build stunning apps and landing pages faster than your peers and competitors.

React navigation is the central feature of a web application by which a user can navigate from one page to another based on his request or some action. From a basic HTML website to a complex application built using frameworks like Reactjs, whenever you want to use URL in your application or react native apps, react navigation comes into play. In this tutorial, we will explore routing or React navigation in depth. At CopyCat, our mission is to convert designs to developer-friendly Reactjs code for you to build UI applications quickly. Build your React projects and mobile apps faster now!

Let’s get started!

How to use Navigate in React

Every popular frontend development framework handles routing in its own way. In a framework like React, where the application is built of various components, React navigation typically means displaying certain screen components based on the URL through conditional rendering.

However, the core React library doesn’t come with a page routing mechanism by default. For this, we need to make use of a library named React Router.

React Router is a library built on top of React for enabling programmatic React navigation by handling routes in a web application. The react navigation library allows the UI to be in sync with the browser URL by conditionally displaying components.

Moreover, it also allows browser functionalities like the back button and page refresh. Using React Router is considered to be the standard routing solution in React and is made use by popular social media mobile apps like Facebook and Instagram. 

Installing react-router-dom

To use React Router in your react app or react native apps, all you need to do is install the dependency.

yarn add react-router-dom

OR

npm install react-router-dom --save   

Note: The current version is React Router v6.

If you are looking for a tutorial for an older version, check out the video below:

In the upcoming sections, we will dive deep into the router configuration for React navigation. On the way, we will also discuss various Router Hooks like

I am assuming that you have a react or react native apps created and configured in your system. If not, refer to this tutorial to set up a basic React or react native apps.

Configuring routes

After installation, now it is time to configure the routes. The steps are as below:

Step 1:

Go to ./src/App.js file inside your project.

Step 2:

Import the following components of react-router-dom inside this js file.

  • BrowserRouter         
  • Route 
  • Routes
import {
  BrowserRouter,
  Routes, //replaces "Switch" used till v5
  Route,
} from "react-router-dom";

Also, import all the components that need to be returned within each route.

Step 3:

Wrap the content of the App component within the <BrowserRouter>.

function App() {
  return (
    <div className="App">
      <BrowserRouter>
        ....
      </BrowserRouter>
    </div>
  );
}

Step 4:

Now within the children content, wrap the part of the UI that needs to conditionally render a certain component based configuration on the URL inside <Routes>.

Within <Routes>, mention each case of <Route> by defining the following attributes:

  • path – for the URL
  • element – for the component that needs to be rendered for that URL

For example, consider an app structure containing a fixed header and fixed footer and the component in between needs to be rendered based on URL. Then the configuration will be as below:

import React from "react";
import {
  BrowserRouter as Router,
  Routes,
  Route,
} from "react-router-dom";
import "./App.scss";
import Footer from "./components/Footer/Footer";
import Header from "./components/Header/Header";
import Home from "./components/Home/Home";
import Dashboard from "./components/Dashboard/Dashboard";
 
function App() {
  return (
    <div className="App">
      <Router>
        <Header></Header>
        <div className="container">
        <Routes>
            <Route path="/" element={<Home />} />
            <Route path="/dashboard" element={<Dashboard />} />
        </Routes>
        </div>
        <Footer />
      </Router>
    </div>
  );
}
 
export default App;

Basic Reactjs Navigation

In this section, let us learn about basic routing in Reactjs. React Router provides us with 2 options to achieve this. 

  • <Link> component
  • useNavigate hook

Using <Link> component

React Router provides a  <Link> component, which can be used for basic React navigation. The <Link> component needs to be passed with a to attribute which specifies the path. Behind the scenes, <Link> renders a <a> with a real href, but it allows us to navigate to a page without reloading the page itself.

When you use CopyCat, we use your existing components so that the exported code is fully functional with your library.

Let us look at a basic React navigation example below:

import { Link } from "react-router-dom";
 
function Header() {
  return (
    <div>
      <h1>My App</h1>
      <nav>
        <Link to="/">Home</Link> |{" "}
        <Link to="about">About</Link>
        <Link to="contact">Contact Us</Link>
      </nav>
    </div>
  );
}

React Router also allows us to define relative links. Relative links are those links that are relative to the component that renders them. They do not start with “/”.

For example, consider the “/dashboard” route which renders the Dashboard component to the user.

function Dashboard() {
  return (
    <div>
      <h1>My Dashboard</h1>
      <nav>
        <Link to="orders">My Orders</Link>
        <Link to="details">My Details</Link>
        <Link to="settings">Settings</Link>
      </nav>
    </div>
  );
}

Within the <Dashboard> component, we have 3 relative links, which are rendered inside of it.

  • dashboard/orders
  • dashboard/details
  • dashboard/settings

One benefit of using the relative link is that, when the parent component URL changes, the links will be automatically updated.

Using useNavigate hook

Alternatively, you can also use the useNavigate hook to achieve basic React navigation.

import { useNavigate } from "react-router-dom";
 
function Login() {
  let navigate = useNavigate();
  return (
    <div>
      <LoginForm
        onSubmit={() => {
          navigate('/user/dashboard');
        }}
      />
    </div>
  );
}

How to configure history using useHistory

Another Router Hook is the useHistory hook, which gives you access to the history instance without pulling it from props.

Let us see an example below:

import { useHistory } from "react-router-dom";
 
const Dashboard = () => {
const history = useHistory();
return (
  <Fragment>
    <h1>Dashboard</h1>
    <button onClick={() => history.push('/') } >Go to Home</button>
  </Fragment>
  )
  };
 
  export default Dashboard;

For a more detailed understanding of useHistory hook and programmatic react navigation , check out this blog. In React navigation, a stack navigator manages React navigation history.

How to add a 404 page to your React App

If the URL matches no path defined by your routes, then you might want the user to redirect to a custom 404 Page Not Found component. Here is how you can do this.


Create a custom <PageNotFound> component. Inside the <Route>, give the path as the wildcard “*” and map it to the <PageNotFound> component.

Remember to place this <Route> at the end, so that for all the URLs for which route is not defined, the <PageNotFound> component gets rendered.

import React from "react";
import {
  BrowserRouter as Router,
  Routes,
  Route,
} from "react-router-dom";
import "./App.scss";
import Footer from "./components/Footer/Footer";
import Header from "./components/Header/Header";
import Home from "./components/Home/Home";
import Dashboard from "./components/Dashboard/Dashboard";
import PageNotFound from "./components/PageNotFound/PageNotFound";
 
function App() {
  return (
    <div className="App">
      <Router>
        <Header></Header>
        <div className="container">
        <Routes>
            <Route path="/" element={<Home />} />
            <Route path="/dashboard" element={<Dashboard />} />
            <Route path="*" element={<PageNotFound />} />
        </Routes>
        </div>
        <Footer />
      </Router>
    </div>
  );
}
 
export default App;

How to navigate to another page in React js

You can also redirect the user to another page. For this, we need to make use of the <Navigate> component.

import { Routes, Route, Navigate } from "react-router-dom";
 
function App() {
  return (
    <Routes>
      <Route path="/home" element={<Home />} />
      <Route path="/" element={<Navigate replace to="/home" />} />
    </Routes>
  );
}

 To get trendy 404 illustrations for your website, checkout this link!

URL Parameters

The URL parameters allow you to declare a placeholder for the dynamic portion of a URL. To deal with the URL parameters, we need to make use of the :style syntax in your route path.

For example, consider the scenario where you want to display a user details page based on his unique user id.

import { Routes, Route } from "react-router-dom";
 
function App() {
  return (
    <Routes>
      <Route
        path="user/:userId"
        element={<User/>}
      />
    </Routes>
  );
}

Here, the :userId plays the role of a URL parameter. Using a single <Route>, we can display a user’s detail based on his user ID in the URL.

How to access URL parameter in a Component

To read the URL parameters in a component, we can make use of the useParams() hooks. Let us see how to access the URL parameter from the previous example.

import { Routes, Route, useParams } from "react-router-dom";
 
function App() {
  return (
    <Routes>
      <Route
        path="user/:userId"
        element={<User/>}
      />
    </Routes>
  );
}
 
function User() {
  let params = useParams();
  return <h1>User Details: {params.userId}</h1>;
}

Nested Routing 

React routers also provided a powerful feature called Nested Routing.

Routes can be nested inside a parent route and their paths will also be nested. This aids in simplifying the code layout.

Let us see a sample code below:

function App() {
    return (
      <Routes>
        <Route path="users" element={<Users />}>
          <Route path=":userId" element={<User />} />
          <Route path="reviews" element={<UserReviews />} />
        </Route>
      </Routes>
    );
  }

In the above code, we have 2 <Route> nested inside a parent <Route>. This route configuration defines 3 paths:

  • “/users”
  • “/users/:userId”
  • “users/reviews”

That is, when the URL is “users/123”, the component tree will be

<App>
  <Users>
    <User />
  </Users>
</App>

And, when the URL is “users/reviews”, the component tree will be:

<App>
  <Users>
    <UserReviews />
  </Users>
</App>

Wrapping Up Reactjs Navigation

React Router is the standard React navigation library for routing solutions in Reactjs. In this React navigation tutorial, we discussed in detail about installation and configuration of the react-router v6. We also learned about various Router Hooks which let you handle routing situations in an easy and elegant way.

CopyCat also helps speed up Reactjs UI development—let us handle the react navigation for you.

Now that you have explored the React Router and its primary capabilities, it is time to use them in your React or React Native apps. Hoping these React navigation examples helped you. To learn deeper about React navigation and routing, check out the video below:

Happy Learning & Keep exploring!

Visit our blog for other interesting and useful articles.

Interesting Reads From Our Blogs

Related Articles

Convert Figma To React

Convert Figma designs to production-ready React.js code. Build stunning apps and landing pages faster than your peers and competitors.

Convert Design to Code