React router navigate and check current route by the key value

Viewed 34

I would like to very nicely ask, if is possible navigate by the route key (not by the route path).

<Suspense fallback={<Loading/>}>
        <Routes>
            <Route path="/" key={"home"} element={<Documents/>}/>

            <Route path="login" key={'login'} element={<PublicRoute>
                <Login/>
            </PublicRoute>}/>

            <Route exact path="/register" key={'register'} element={<PublicRoute>
                <Register/>
            </PublicRoute>}/>

            <Route exact path="/invitation/:tokenAffilRecommender" key={'invitation'} element={<PublicRoute>
                <Register/>
            </PublicRoute>}/>

            <Route exact path="/forgot" key={'forgotPassword'} element={<PublicRoute>
                <ForgotPassword/>
            </PublicRoute>}/>
</Routes>
</Suspense>

...And I tried to navigate by the following way:

....
const navigate = useNavigate();

...
<a href="#" onClick={event => {
event.preventDefault();
navigate('login'); // I was thinking, that first parameter is the key, not the url path, therefore it not works :-(

navigate('/login') // It works, but I don't want to have on each navigate the whole url path :-(

}}>Click!</a>

and, also I don't know, how to check, which route is currently active by the key name :-(

...
const location = useLocation();

const pathname = location.pathname; // Gets the path, but I need to know key of the route defined in routes, not whole url path

Thanks a lot for an each help :-)

0 Answers
Related