go back in react router dom

Go Back in React Router Dom

If you are using React Router Dom in your web application, you may have encountered situations where you need to go back to the previous page or route. React Router Dom provides us with a simple and easy way to accomplish this task.

Using History

The easiest way to go back in React Router Dom is by using the history object. The history object is provided by the React Router Dom and contains the navigation history of the application.


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

function MyComponent() {
  const history = useHistory();

  function goBack() {
    history.goBack();
  }

  return (
    <div>
      <button onClick={goBack}>Go Back</button>
    </div>
  );
}

In the example above, we use the useHistory hook to get access to the history object. We then create a function called goBack that calls the goBack() method of the history object when the user clicks on a button.

If you want to go back to a specific page or route, you can use the Link component from React Router Dom. The Link component creates a hyperlink to a specific route in your application.


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

function MyComponent() {
  return (
    <div>
      <Link to="/previous-page">Go Back</Link>
    </div>
  );
}

In the example above, we use the Link component to create a hyperlink to the /previous-page route in our application. When the user clicks on the link, they will be taken to the previous page or route.

Using Redirect

If you want to go back to a specific page or route programmatically, you can use the Redirect component from React Router Dom. The Redirect component allows you to redirect the user to a specific route in your application.


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

function MyComponent() {
  const shouldRedirect = true;

  if (shouldRedirect) {
    return <Redirect to="/previous-page" />;
  }

  return <div>Hello World!</div>;
}

In the example above, we use the Redirect component to redirect the user to the /previous-page route if the shouldRedirect variable is true. If the variable is false, we simply render a <div> with the text "Hello World!".

These are some ways you can go back in React Router Dom. Choose the one that suits your needs and implement it in your application.

Subscribe to The Poor Coder | Algorithm Solutions

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.
[email protected]
Subscribe