Borislav Hadzhiev
Sat Apr 30 2022·2 min read
Photo by Jossemio
To create a back button with React Router:
onClick
prop on a button to a function.useNavigate()
hook, e.g. const navigate = useNavigate();
.navigate()
function passing it -1
- navigate(-1)
.import {Link, Routes, Route, useNavigate} from 'react-router-dom'; export default function App() { const navigate = useNavigate(); return ( <div> <button onClick={() => navigate(-1)}>Go back 1 Page</button> <button onClick={() => navigate(1)}>Go forward 1 Page</button> <div> <nav> <ul> <li> <Link to="/">Home</Link> </li> <li> <Link to="/contacts">Contacts</Link> </li> </ul> </nav> {/* 👇️ Wrap your Route components in a Routes component */} <Routes> <Route path="/contacts" element={<Contacts />} /> <Route path="/" element={<Home />} /> </Routes> </div> </div> ); } function Home() { return <h2>Home</h2>; } function Contacts() { return <h2>Contacts</h2>; }
The useNavigate hook returns a function that lets us navigate programmatically, e.g. after a form is submitted or a button is clicked.
-1
as a parameter to the navigate()
function, e.g. navigate(-1)
.Calling navigate
with -1
is the same as hitting the back button in the
browser.
Similarly, you can call the navigate
function with -2
to go 2 pages back.
You can also use the navigate
function to programmatically navigate to a
different route, e.g. navigate(/contacts)
.
import {useNavigate} from 'react-router-dom'; export default function App() { const navigate = useNavigate(); const handleClick = () => { // 👇️ replace set to true navigate('/contacts', {replace: true}); }; return ( <div> <button onClick={handleClick}>Navigate to /contacts</button> </div> ); }
When the replace
property is set to true
on the options object, the current
entry in the history stack gets replaced with the new one.
This is useful, for example, when a user logs in - you don't want them to be able to click the back button and get back to the login page.
Or if you have a route that redirects uses to a different page - you don't want users to click the back button and get redirected again.
If you need to navigate one page forward, call navigate
with 1
-
navigate(1)
.
To use the useNavigate
hook in your application, make sure the App
component
in your index.js
file is wrapped in a Router
.
import {createRoot} from 'react-dom/client'; import App from './App'; import {BrowserRouter as Router} from 'react-router-dom'; const rootElement = document.getElementById('root'); const root = createRoot(rootElement); // 👇️ wrap App in Router root.render( <Router> <App /> </Router> );
Router
component is in your index.js
file because that's the entry point of your React application.Once your entire app is wrapped with a Router
component, you can use any of
the hooks from the react router package anywhere in your components.