ReactJS Login page repeating on every url path

Viewed 47

Here is my code, I am completely new to front end development can any one help me solve the issue, I want the user to be redirected to the login page if the user is not logged in but once he is logged in every thing should work fine but even when I click sign in, the login page shows up when I change the URL, The login page is appearing on every URL Here's my code (i am new to front end pls dont judge)

import { useState } from 'react'
import { Route, Switch} from 'react-router-dom'
import Dashboard from "./pages/Dashboard";
import DatasetGenerator from "./pages/DatasetGenerator"
import Simulator from "./pages/Simulator"


function App() {
  
  const [login, setlogin] = useState(true)
  const [homepage, setHomepage] = useState(false) 
const loginHandler = ()=>{
  if(login == true){setlogin(false)
  setHomepage(true)}
}


  return ( 
    <div>
    {login && <SignIn loginHandler={loginHandler} />}
    <Switch>
      

      <Route path='/' exact>
        {homepage && <Dashboard />}
      </Route>
      <Route>
      {homepage &&  <DatasetGenerator path="/dataset-generator"/>}
      </Route>
      
      <Route path="/simulator">
      {homepage &&  <Simulator  />}
      </Route>
    </Switch>
    </div>
  )
  }

export default App;
1 Answers

Seems like you want to conditionally render the login component OR the rest of your app. Since the login state and the homepage state appear to be mutually exclusive you probably don't need both (though perhaps we're missing some context).

return ( 
  <div>
    {login ? (
      <SignIn loginHandler={loginHandler} />
    ) : (
      <Switch>
        <Route path='/' exact>
          <Dashboard />
        </Route>
        <Route>
          <DatasetGenerator path="/dataset-generator"/>
        </Route>
        <Route path="/simulator">
          <Simulator  />
        </Route>
      </Switch>
    )}
  </div>
)

A better solution would be to implement an auth workflow by creating authenticated route components that handle redirecting to a login route if not authenticated, otherwise allows the user to access the route.

Related