I would to for the URL in the adress bar to show "/login" when im in the login page.
// App.js
<Routes>
{isLoggedIn ? (
<Route path="/" element={<Root onLogout={handleLogout} />}>
<Route index element={<Topics />} />
<Route path="employees" element={<EmployeeList />} />
<Route path="employees/create" element={<RegisterEmployee />} />
<Route path="employees/:employeeId" element={<EditEmployee />} />
<Route path="user-entry" element={<Register />} />
<Route path="dashboard" element={<Dashboard />} />
</Route>
) : (
<Route path="/" element={<Login onLogin={handleLogin} />} />
)}
</Routes>
// index.js
ReactDOM.render(
<React.StrictMode>
<Provider store={store}>
{/* Using HashRouter(which introduces "#" in the URL) because when BrowserRouter is used, and the any page is refreshed, the app throws an error(Cannot Get) */}
<Router>
<Routes>
<Route path="/*" element={<App />} />
</Routes>
</Router>
</Provider>
</React.StrictMode>,
document.getElementById("app")
);
The above is working fine with exception that I need the path to be "/login", and when i change it, the page is blank, nothing is mounted.
The other paths are supose to be like the above, for the exception of the login.
Could anyone shed some light?
2
Answers
The best practice would be to use
Navigate
component from"react-router-dom"
To show "/login" in the address bar you must create a route for "/login" with
<Login onLogin={handleLogin}/>
element.Then you can use
useNavigate()
hook fromreact-router
to redirect the user to "/login" if the user is not logged in, do this in a side effect (useEffect).There are many ways to implement this, it all depends on your requirements. You must also consider protecting your routes from unauthenticated users.