Categories
React Answers

How to go back a page with React Router v6?

Spread the love

To go back a page with React Router v6, we use the useNavigate hook.

For instance, we write

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

function App() {
  const navigate = useNavigate();

  return (
    <>
      <button onClick={() => navigate(-1)}>go back</button>
      <button onClick={() => navigate(1)}>go forward</button>
    </>
  );
}

to call useNavigate to return the navigate function.

Then we call navigate with -1 to go back to the previous page.

We can also call navigate with 1 to go to the next page in the history.

Conclusion

To go back a page with React Router v6, we use the useNavigate hook.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published.