简体   繁体   中英

Redirect in React Router Dom v6

I need help after the update from React Router Dom to version 6. I have a code snippet for redirects after a user logged in which should work in version 5, but I think "Redirect" is depreceated. Now, I am looking for some replacement which integrates into my former code.

Here is my code example which should work in React Router Dom version 5:

<Route path='/signin' render={() => this.props.currentUser? (<Redirect to =''/>): (<SignIn/>)}></Route>

I think I should use something like "Navigate", but I am not sure how to implement this with the conditional statement since for version 6 I also would have to add the "element={}" part.

Let me know in case you need more information.

Thanks!

The new pattern for handling "authentication" or essentially conditional routing/redirecting is to use a wrapper component to handle the conditional logic and return the child or the Navigate .

const SignInWrapper = ({ children, currentUser }) => {
  return currentUser ? <Navigate to="/" replace /> : children;
};

...

<Route
  path='/signin'
  element={<SignInWrapper currentUser={this.props.currentUser}>
    <SignIn />
  </SignInWrapper>}
/>

I want to redirect user to the page, from which he was redirected. How can i do that using this code in V6?

const PrivateRoute = ({ children, ...rest }) => { 


let {user} = useAuth();
  return (
   user.displayName ? (children):(<Navigate to='/login' />)
  )
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM