Create a Back button with React Router

To create a back button with React Router use useNavigate() hook. We can navigate to the previous page programmatically by using the useNavigate hook. Call navigate function with an argument -1 eg. navigate(-1); inside the onClick event handler function of the back button.

In this article, we are going to discuss this with an example code. Besides the browser’s back button, our custom back button will add convenience and optimize the user experience.

To create a back button using useNavigate() hook with React Router follow the below steps.

  1. Set the onClick event handler function for a button.
  2. Use the useNavigate() hook, eg. const navigate = useNavigate();.
  3. Call navigate function with -1 as an argument inside the event handler function. eg. navigate(-1)

Let us discuss this with below example code.

import React from 'react';
import {Route, Link, Routes, useNavigate} from 'react-router-dom';

export default function App() { 
  return (
		<>
			<ul>
				<li>
					<Link to="/">Home</Link>
				</li>
				<li>
					<Link to="/about">about</Link>
				</li>
			</ul>
			<Routes>		
				<Route path="/about" element={<About/>} />
				<Route path="/" element={<Home/>} />
			</Routes>
		</>
	);
}

function Home() {
  	return <>		
		<p>Home Page</p>
	</>;
}

function About() {
	const navigate = useNavigate();
	const goBack = () => {
		navigate(-1);
	}
	return <>	
		<button onClick={goBack}>Back</button>	
		<p>About Page</p>
	</>;
}

In the above code, we imported useNavigate from react-router-dom. The useNavigate hook returns a function that lets us navigate programmatically. By calling navigate(-1);the page will redirect to the previous page. Similarly, If we want to go back to more than one page, replace -1 with -2, -3, etc.

If we want to move one page forward, we can call navigate(1);.

To use useNavigate() hook, make sure to wrap the entire App component with the BrowserRouter component as given below.

import React from 'react';
import ReactDOM from 'react-dom/client';
import App from './App';
import reportWebVitals from './reportWebVitals';
import { BrowserRouter } from 'react-router-dom';

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

reportWebVitals();

In the above code, we imported BrowserRouter from react-router-dom and wrapped the entire app with this BrowserRouter component. Since we are wrapping the entire App from index.js with the BrowserRouter, we can use any react-router-dom hooks anywhere in the application.

Similarly, we can use useNavigate() hook to navigate to another page on a button click or any other event. In the below example, we are navigating to the product page with a button click.

import { useNavigate } from 'react-router-dom';

function About() {
	const navigate = useNavigate();
	const clickHandler = () => {
		navigate('/product', {replace: true});
	}
	return <>	
		<button onClick={clickHandler}>Go to product</button>	
		<p>About Page</p>
	</>;
}

The second argument {replace: true} is for the current entry in the history stack to get replaced with the new URL. This means, the browser history was replaced with a new URL and when the user clicks on the back button it will not redirect to the previous page.

Conclusion

To create a back button with React Router, use the useNavigate() hook from react-router-dom. 

Use the useNavigate() hook, eg. const navigate = useNavigate();. Call navigate function with -1 as an argument eg. navigate(-1);  when the back button was clicked. We can use useNavigate() hook to navigate to any other pages programmatically.

Related Blogs

Can't Perform a React State Update on an Unmounted Component

Can't Perform a React State Update on an Unmounted Component

React Warning “Can't perform a react state update on an unmounted component” is caused when we try to update the state after the component was unmounted. Explains how to fix it.

Each child in a list should have a unique key prop

Each child in a list should have a unique key prop

Solve Warning: Each child in a list should have a unique ”key" prop in React by setting the id property as a unique key or by auto-assigning unique keys.

React Hook is Called Conditionally

React Hook is Called Conditionally

Error: "React Hook is called conditionally. React Hooks must be called in the exact same order in every component render" occurs when hooks are invoked conditionally or after a return of a value.

Too many re-renders. React limits the number of renders to prevent an infinite loop

Too many re-renders. React limits the number of renders to prevent an infinite loop

The React error "Too many re-renders. React limits the number of renders to prevent an infinite loop" happens when you have reached an infinite render loop.

Adjacent JSX elements must be wrapped in an enclosing tag

Adjacent JSX elements must be wrapped in an enclosing tag

The "Adjacent JSX elements must be wrapped in an enclosing tag" error can be solved by wrapping the multiple elements in a parent div or in a react fragment

The tag is unrecognized in this browser

Warning: The tag is unrecognized in this browser

Warning "The tag is unrecognized in this browser" occurs when the tag doesn't exist in the browser or when we render a component starting with a lowercase letter.

The style prop expects a mapping from style properties to values, not a string

The style prop expects a mapping from style properties to values, not a string

"The style prop expects a mapping from style properties to values, not a string" React error occurs when we pass a CSS string to the style attribute.

Pass event and parameter onClick in React

How to pass event and parameter onClick in React

We set the inline arrow function (event) => clickHandler(event, "Hello World!") as props to the onClick event handler in the button. The arrow function takes the event as an argument and calls the clickHandler function.

Call multiple functions onClick in React

Call multiple functions onClick in React

To call multiple functions onClick in React, pass an event handler function into the onClick prop of the element that can call as many other functions as necessary.