React router 6 go back: How to go back using react router v6

·

2 min read

React Router is a popular library for adding routing to a React application. Version 6 of React Router introduced a number of changes, including a new way to navigate back to a previous page.

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

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

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

To go back to a previous page in React Router v5, you can use the history object. This object is automatically passed to your React components when you use the withRouter higher-order component from React Router. You can then call the goBack method on the history object to navigate back to the previous page.

Here's an example of how to use the goBack method in a React component:

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

function MyComponent(props) {
  // Get the history object from the props
  const { history } = props;

  // Call the goBack method to go back to the previous page
  history.goBack();

  return (
    <div>
      {/* Your component JSX here */}
    </div>
  );
}

// Wrap your component with the withRouter higher-order component to
// get access to the history object
export default withRouter(MyComponent);

You can also pass a specific number of pages to go back as an argument to the goBack method. For example, to go back two pages, you can call history.goBack(2).

In addition to the goBack method, the history object also has other methods for navigating around your React application, such as push for navigating to a new page, and replace for replacing the current page with a new one.

React Router 6 makes it easy to add routing to your React application, and the history object provides a simple way to navigate between pages. By using the goBack method, you can easily go back to a previous page in your application.