ExtraSun
ExtraSun

Reputation: 548

Protected routes for react router v5 isn't working

I'm trying to create a protected/private route with react-router-dom v5, as in the link here, I use only the code I needed - Protected routes and authentication with React Router v5.
Now I need both components private from each other
The problem: after Getting Home component transferred fromSignUp components I can go back to SignUp and thats not what I want.

Signup corrently is the first page (as sign-in). I don't want the user to go back to sigh-up components if he already signed up and present at the Home component.

The working website project is here - CodeSandbox
Anyone has idea how can I make both component protected/private?

GuardedRoute.jsx

function GuardedRoute({ children, auth, ...rest }) {
  return (
    <Route
      {...rest}
      render={() => {
        return auth === true ? children : <Redirect to="/signup" />;
      }}
    />
  );
}

export default GuardedRoute;

App.js

const App = () => {
  const [userID, setUserID] = useState('');
  const [userSignedUp, setIfSignUp] = useState(false);
  return (
    <div className="App-div">
      <GuardedRoute exact path="/home" auth={userSignedUp}>
        <Home userIDNumber={userID} setIfSignUp={setIfSignUp} />
      </GuardedRoute>
      <Switch>
        <Route path="/signup">
          <SignUp setUserNumber={setUserID} setIfSignUp={setIfSignUp} />
        </Route>
      </Switch>
    </div>
  );
};

export default App;

Please try any of your solutions at my codesandbox before posting your answer so we will not try solutions in theory only and in vain :)

Upvotes: 0

Views: 1533

Answers (1)

Gabriele Petrioli
Gabriele Petrioli

Reputation: 195992

You could make the signup route only exist if the user is not logged in, and then use a catch-all that will redirect to /home

<div className="App-div">
  <Switch>
    {!userSignedUp && (
      <Route path="/signup">
        <SignUp setUserNumber={setUserID} setIfSignUp={setIfSignUp} />
      </Route>
    )}
    <GuardedRoute path="/home" auth={userSignedUp}>
      <Home userIDNumber={userID} setIfSignUp={setIfSignUp} />
    </GuardedRoute>

    <Route path="/">
      <Redirect to="/home" />
    </Route>
  </Switch>
</div>

Updated sample: https://codesandbox.io/s/jolly-https-t7dmj?file=/src/containers/App.js


or you could encapsulate the logic to another component like GuardedRoute, let say UnguardedRoute that will redirect somewhere if user is logged in.

Upvotes: 1

Related Questions