Search code examples
javascriptreactjsreact-router-dom

React Router Dom, useNavigate not redirecting to the right url path


In older React Router Dom versions, I was able to use this code to redirect if a user is logged in:

history.push('/login?redirect=shipping')

Now in v6, I am using the useNavigate functions instead of history.push, but it's not working as it is taking me to /login/shipping instead of /shipping. Currently, this is my navigate code:

let navigateCart = useNavigate() 
// some code here
navigateCart('/login?redirect=shipping') // the mistake is inside the parenthesis here but I don't know what it is!

This is my router config:

<BrowserRouter>
  <Container>
    <Routes>
      <Route path="/" element={<HomeScreen />} exact />
      <Route path="/login" element={<LoginScreen />} />
      <Route path="/profile" element={<ProfileScreen />} />
      <Route path="/shipping" element={<ShippingScreen />} />
    </Routes>
  </Container>
</BrowserRouter>

Login Screen Function :

function LoginScreen() {

    let navigateLog = useNavigate()
    let location = useLocation()

    const [email, setEmail] = useState('')
    const [password, setPassword] = useState('')

    const dispatch = useDispatch()

    const redirect = location.search ? location.search.split('=')[1] : '/'
    

    const userLogin = useSelector(state => state.userLogin)
    const { error, loading, userInfo } = userLogin


    useEffect(() => {
        if (userInfo) {
            navigateLog(redirect)
        }
    }, [navigateLog, userInfo, redirect])

    const submitHandler = (e) => {
        e.preventDefault()
        dispatch(login(email, password))
    }

Solution

  • Change that navigateLog(redirect) line inside the useEffect in LoginScreen to this one:

    navigateLog(`/${redirect}`);
    

    In your case, it's redirecting to /login/shipping instead of /shipping, cause it's like you are calling navigateLog("shipping"), and without / in front, it's used as a relative path. This means it takes into account your current path, which in your case happens to be /login.

    Edit angry-fast-upe615