2

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!

Anne
  • 121
  • 1
  • 7

2 Answers2

5

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>}
/>
Drew Reese
  • 165,259
  • 14
  • 153
  • 181
0

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' />)
  )
}
Skatox
  • 4,237
  • 12
  • 42
  • 47
  • I do not get this post. Are you answering the question which you wrote at the start of this post? Or are you answering the question at the top of this page? They do not seem to be the same. Or are you in fact hoping that someone answers your question instead of the one asked on this page? Please [edit] to make the point of this post more obvious - ideally according to [answer]. – Yunnosch May 04 '22 at 19:50