Check if you can go back when using react-router MemoryRouter?

Advertisements

I’m using react-router v6 (ie. with useNavigate, and no useHistory available).

My app is all setup inside a MemoryRouter like this:

     <MemoryRouter >
              <Routes>
                <Route path="/" element={<Popup />} />
                <Route path="/user/:userid" element={<UserProfilePage />} />
                <Route path="/register" element={<RegisterForm />} />
                <Route path="/login" element={<LoginSection />} />
                <Route path="/reset-password" element={<ResetPasswordForm />} />
              </Routes>
    </MemoryRouter>

I’m trying to create a "Go back" button that takes you back to where you were previously. This is what the button looks like:

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

export default function BackButton() {
    const navigate = useNavigate();
    const canGoBack = ???

    return (
        <button onClick={() => navigate(-1)} disabled={!canGoBack}>
            Go Back
        </button>
    );
}

The navigate(-1) works fine and takes you back to the previous back. However, I’m trying to figure out how to derive canGoBack? I’d like the button to be disabled if there’s nowhere to go back.

>Solution :

You can use useLocation to determine whether can go back or not. It has a property called key which has two values one is default means you can’t go back obviously you come from outside the app or new tab and another one is unique key of that location that means you are routed inside the app.

import React from "react";
import { useNavigate, useLocation } from "react-router-dom";

export default function BackButton() {
    const navigate = useNavigate();
    const location = useLocation();
    const canGoBack = location.key === 'default';

    return (
        <button onClick={() => navigate(-1)} disabled={canGoBack}>
            Go Back
        </button>
    );
}

Leave a ReplyCancel reply