Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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>
    );
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading