user16524267
user16524267

Reputation:

Redirect react-router-dom v6

I have a problem, watching a video on youtube that used history.push('/login?redirect=shipping'), how can I modify it using navigate, because if I use the string navigate ('/ login?redirect=shipping') even if logged in it returns to home page and does not go to the shipping page.

I solved the problem in this way :

 const checkoutHandler = () => {
       if(!userInfo){
          navigate('/login')
       } else{
          navigate('/shipping')
       }
    }

Upvotes: 1

Views: 1293

Answers (5)

user3159368
user3159368

Reputation: 1

const checkoutHandler = ()=>{
        navigate('/login?redirect=/shipping')
}

Upvotes: 0

Sangam Giri
Sangam Giri

Reputation: 11

Try this one...

navigate ('/login?redirect=/shipping')

Add forward slash '/' after redirect= before shipping, Doing so, first login route will be executed then it will redirect to shipping.

Upvotes: 1

elfsvet
elfsvet

Reputation: 36

Your solution is good. Can I fill in some gaps?

  1. We need to get the state of user to check if user logged in to proceed with if statement.

  2. After this your solution will work.

    import React from 'react'
    import { useNavigate } from 'react-router-dom'
    import { useSelector } from 'react-redux'
    //....some imports
    
    const CartScreen = () => {
    //.......some code before
      const navigate = useNavigate()
      const userLogin = useSelector((state) => state.userLogin)
      const { userInfo } = userLogin
    
      const checkoutHandler = () => {
        if (!userInfo) {
        navigate('/login')
        } else {
          navigate('/shipping')
        }
      }
    
      //...return JSX...
    

Upvotes: 2

Abdul Mateen
Abdul Mateen

Reputation: 1

Have you sort out this problem or not? If you are facing the same problem then I suggest you go on your login page and make some changing.

Import useHistory and useLocation:

import { Link, useHistory, useLocation } from 'react-router-dom'

Then in functions apply this:

const history = useHistory();
const location = useLocation();

Upvotes: 0

minhaj
minhaj

Reputation: 37

**Try this one.

const navigate = useNavigate()
const checkoutHandler = () => {
    navigate('/signin?redirect=/shipping')
}

Upvotes: 2

Related Questions