How To Go Back To The Previous Page With React Router

Go back to the previous page with React Router

Although React isn’t made for multi-page applications, you can totally go back to the previous page with React Router. This guide will show you how to do that.

Go back to the previous page with React Router

React is designed to create single-page web applications, meaning that by default it doesn’t have any routing and navigation capabilities. It renders all the elements on a single page (index.html). To break your app into different pages and navigate between them with the browser’s back or forward buttons, you will need to rely on other libraries.

React Router is the most popular choice for client-side routing. Install the react-router-dom to your project first:

npm install react-router-dom

Let’s create a simple React site that uses routing functionality from React Router.

You will need to import some interfaces from the module:

import ReactDOM from "react-dom/client";
import { BrowserRouter, Routes, Route, Outlet, Link, useNavigate } from "react-router-dom";

Now, we define the routing of your web page with BrowserRouter, Routes, And Route:

export default function App() {
    return (
        <BrowserRouter>
            <Routes>
                <Route path="/" element={<Layout />}>
                    <Route index element={<Home />} />
                    <Route path="about" element={<About />} />
                </Route>
            </Routes>
        </BrowserRouter>
    );
}

const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(<App />);

In this example, the <Layout> component renders common elements that should appear on every page. We assign it to the first <Route> component with the root path ‘/‘. Inside it, we nest two other elements, which render the <Home> and <About> components respectively.

We create simple HTML elements for these React components:

const Home = () => {
	return <p>Welcome to LearnShareIT. This is our homepage.</p>;
};

const About = () => {
    return (
      	<>
            <h2>About Us</h2>
            <p>LearnShareIT is a knowledge portal for programmers.</p>
        </>
    );
};

To demonstrate the routing and navigation capabilities of React Routers, we add two buttons (‘Go back’ and ‘Go forward’) in the <Layout> component. They should appear at the end of the pages. There is also a list containing the links to our Home and About pages.

const Layout = () => {
    const navigate = useNavigate();
  
    return (
        <>
          <h1>LearnShareIT</h1>
          <nav>
              <ul>
                  <li>
                      <Link to="/">Home</Link>
                  </li>
                  <li>
                      <Link to="/about">About</Link>
                  </li>
              </ul>
          </nav>
          <Outlet />
          <p>Click the buttons below to see how navigation works in React Router:</p>
          <button onClick={() => navigate(-1)}>Go back</button>
          <button onClick={() => navigate(1)}>Go forward</button>
        </>
    );
};

Notice how we use the useNaviage() hook, which belongs to the react-router-dom module. It returns a function that allows you to programmatically navigate the browser by using the History API under the hood.

In the above example, we use it to pass the delta we need to the browser’s history stack when a button is pressed. The navigate(-1) call is equivalent to pressing the back button of your browser.

This is what the home page looks like:

Now we click the link to go to the About page. The content of the page changes, and the address bar will become http://localhost:3000/about:

When you want to go back, there are two options: Click the back button on your browser’s toolbar, or click the ‘Go back’ button on the web page. They have the same effect, and both bring you back to the previous page:

The useNaviage() hook works like the go() method in the History API, which loads the desired page from your session history. Depending on the value of your parameter, it can move you backward or forward through the browser’s history.

Keep in mind that the delta value is relative to your current page. Negative values mean going backward, and positive values going forward. For instance, the value 1 moves one page forward, which you can test by using the ‘Go forward’ button on the example.

Summary

To go back to the previous page with React Router, you can use the useNavigate() hook. It allows you to go backward and forward through the session history depending on the delta parameter you provide.

Maybe you are interested:

Leave a Reply

Your email address will not be published. Required fields are marked *