close

How to go back to previous route in react-router-dom v6?

Today in this tutorial we are Going to talk about How to go back to previous route in react-router-dom v6? When we are using react-router-dom how we can go back to the previous page because the latter version of react-router-dom has history.goBack() and that is not working in react-router-dom v6.

How to go back to previous route in react-router-dom v6?

  1. How to go back to previous route in react-router-dom v6?

    To go back to previous route in react-router-dom v6 First of all, you need to import useNavigate from react-router-dom and then you can use navigate(-1) to go back to the previous version If You want to Go 2 pages back then probably you have to use navigate(-2). If you want to Go forward one Page then same you can use navigate with a positive number navigate(1) and to Go 2 pages forward you can use navigate(2). Hope now you understand How to go back to previous route in react-router-dom v6. Thank you.

  2. go back to previous route in react-router-dom v6

    To go back to previous route in react-router-dom v6 First of all, you need to import useNavigate from react-router-dom and then you can use navigate(-1) to go back to the previous version If You want to Go 2 pages back then probably you have to use navigate(-2). If you want to Go forward one Page then same you can use navigate with a positive number navigate(1) and to Go 2 pages forward you can use navigate(2). Hope now you understand How to go back to previous route in react-router-dom v6. Thank you.

Method 1: Use navigate(-1)

First of all, you need to import useNavigate from react-router-dom and then you can use navigate(-1) to go back to the previous version If You want to Go 2 pages back then probably you have to use navigate(-2). If you want to Go forward one Page then same you can use navigate with a positive number navigate(1) and to Go 2 pages forward you can use navigate(2). Here is my example.

import { useNavigate } from 'react-router-dom';  // Import react-route-dom
 
function App() {

  const navigate = useNavigate();  // make const
 
  return (
    <>
      <button onClick={ () => navigate(-2) }>Go 2 pages back</button>
      <button onClick={ () => navigate(-1) }>Go 1 pages back</button>
      <button onClick={ () => navigate(1) }>Go 1 Page forward</button>
      <button onClick={ () => navigate(2) }>Go 2 pages forward</button>
    </>
  );
}

Hope now you understand How to go back to previous route in react-router-dom v6. Thank you.

Conclusion

It’s all About this article. Hope this method worked for you. Comment below Your thoughts and your queries. Also, Comment below which method worked for you?

Also, Read

Leave a Comment