Home > Mobile >  how to redirect in react v6
how to redirect in react v6

Time:12-18

I need to navigate back to the original requested URL after login.

For example, the user enters www.eCart.com/Cart as the user is not authenticated, it will navigate to the login page www.eCart.com/login.

Once authenticated, it should navigate back to www.eCart.com/Cart automatically

my protectedRoute.js looks like this

import React from 'react'
import { connect } from 'react-redux'
import { Navigate, Outlet, useLocation, useNavigate} from 'react-router-dom'

export const withRouter = (Component) => { //works only for react16-17 //hooks
    const Wrapper = (props) => {
        const location = useLocation()
        const navigate = useNavigate();
        return (
            <Component
                navigate = {navigate}
                {...props}
                location={location}
                {...props}
            />
        );
    };

    return Wrapper;
};

const ProtectedRoute = ({component:Component, auth,...rest}) => (

    auth.isAuthenticated ? <Outlet /> : <Navigate to={`/login/${rest.location.search}`} replace />
    
)

const mapStateToProps = (state) => ({
    auth: state.auth
})

export default connect(mapStateToProps)(withRouter(ProtectedRoute))

my app.js is like this

function App(props) {
  useEffect(() => {
    store.dispatch(setCurrentUser())
  }, [])

  const grabProductsFromStorage = () =>{
    const userId = decodeUser().user.id
    const cartProducts = JSON.parse(localStorage.getItem("products"))
    const context = {products: cartProducts, userId}
    store.dispatch(addToCart(context))
    localStorage.removeItem("products")
  }

  if(localStorage.getItem("token") && localStorage.getItem("products")){
    grabProductsFromStorage()
  }

  return (
    <Provider store={store}>
      <Router>
        <Routes>
        <Route exact path="/" element={<Landing/>} />
        <Route exact path="/products/:id" element={<ProductDetails/>} />
          <Route exact path="/" element={<ProtectedRoute/>}>  
            <Route  exact
              path="/dashboard/*" 
              element={<Dashboard {...props} nestedRoute={Home} />} 
            />
            <Route exact path="/cart" element={<Cart />} />
          </Route>
          <Route exact path="/register" element={<Register/>} />
          <Route exact path="/login" element={<Login/>} />
        </Routes>
      </Router>
    </Provider>

  );
}

Also, I've seen somewhere to use state in Navigate with the location it but when I'm doing it it's throwing an error of Unexpected use of 'location'

CodePudding user response:

You need to store that cart route first. while redirecting to login page from the cart if a user is not authenticated & redirected to the login page you need to store the cart route in your localstorage or somewhere in your state so after login you can check do we have afterlogin route then you can redirect the user to that page.

CodePudding user response:

There are some approaches:

Redirect user to another page:

 function Redirect() {
  let navigate = useNavigate();
  function handleClick() {
    navigate('/home')
  }
  return (
    <div>
      <button onClick={handleClick}>go home</button>
    </div>
  );
}

redirect to previous page

function Redirect() {
  let navigate = useNavigate();
  function handleClick() {
    navigate(-1)
  }
  return (
    <div>
      <button onClick={handleClick}>go home</button>
    </div>
  );
}

redirect user to the next page

function Redirect() {
  let navigate = useNavigate();
  function handleClick() {
    navigate(1)
  }
  return (
    <div>
      <button onClick={handleClick}>go home</button>
    </div>
  );
  • Related