Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Handle back button with react router

If a user navigates to www.example.com/one and clicks the back button, I want to redirect them to www.example.com.

I think it's a common problem, but I haven't found a solution yet.


2 Answers

In react-router-dom v6 useHistory() is replaced by useNavigate(). so use useNavigate() inplace of useHistory() this way.

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

export const Item = () => {
    let navigate = useNavigate();
    return (
        <>
          <button onClick={() => navigate(-1)}>Back</button> 
        </>
    );
};

for more on useNavigate visit this: https://reactrouter.com/docs/en/v6/hooks/use-navigate

like image 99
Ajay jangid Avatar answered Sep 05 '25 01:09

Ajay jangid


Hooks version (React 16.8+):

Minimal version.

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

export const Item = () => {
    let history = useHistory();
    return (
        <>
          <button onClick={() => history.goBack()}>Back</button>
        </>
    );
};
like image 43
Hunter Avatar answered Sep 05 '25 00:09

Hunter



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!