Home > Software design >  Redirect in React Router Dom v6
Redirect in React Router Dom v6

Time:11-20

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!

CodePudding user response:

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