2

Suppose we have this situation:

<Routes>
    <Route path="/" element={<Master/>}/>
    <Route path="/login" element={<Auth/>}>
        <Route path="" element={<AuthInitiate/>}/>
        <Route path="callback" element={<AuthCallback/>}/>
    </Route>
</Routes>

Suppose we currently are in /login/callback. Inside the AuthCallback component I use:

const navigate = useNavigate()
navigate("/")

The result is that i get redirected to /login, so I understand that the "/" refers to the relative subroute we are in (that is, /login). This is super useful in a lot of situations, but here I just to redirect with respect to the absolute path, so "/" should mean exactly / and not /login.

How should I do?

Be aware I'm referring to the new React Router v6.

EDIT: I had something else redirecting the route, the code instead works exactly as expected and navigate("/") from subroute indeed navigate to root level. There are no issues with navigation from subroutes, sorry.

edoedoedo
  • 1,469
  • 2
  • 21
  • 32
  • 1
    I'm unable to reproduce the behavior you describe with the code you've shared. Check this running [codesandbox](https://codesandbox.io/s/react-router-v6-navigate-to-absolute-path-from-subrouter-o0vxy?file=/src/App.js) demo that appears to navigate absolutely to `"/"` from `"/login/callback"`. – Drew Reese Nov 16 '21 at 17:06
  • You're right I was wrong there were something else misbehaving in my router configuration, sorry about that. – edoedoedo Nov 19 '21 at 10:02
  • Do you still have an issue? If so can you update your question to include the new details? – Drew Reese Nov 19 '21 at 16:36
  • 1
    Updated the question with the details, it was a false problem, your codesandbox works exactly as intended. – edoedoedo Nov 22 '21 at 17:21

2 Answers2

2

Even though OP's problem is already resolved, I think it may be worth leaving this answer here for future travelers:

Use a leading slash to navigate to an absolute path:

const navigate = useNavigate();

// Absolute path:
navigate('/login/auth');

// Relative paths:
navigate('login');
navigate('login/auth');
navigate('../login');

Also noteworthy: In React Router v6 trailing slashes are ignored.

Michael Johansen
  • 4,688
  • 5
  • 29
  • 47
1

https://reactrouter.com/en/main/hooks/use-navigate

It states that

if you want relative path use

const navigate = useNavigate()
navigate('users')

if not then use

const navigate = useNavigate();
navigate('/dashboard/users')