'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!



Solution 1:[1]

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>}
/>

Solution 2:[2]

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' />)
  )
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Drew Reese
Solution 2 Skatox