Problem when reloading page using react-router-dom - reactjs

I managed to make a private route and navigate to different pages using react-router-dom. How ever, when I navigate to a page and reload it, it first goes to /login for half a second and the reloads the page correctly. How can I prevent this unwanted behavior and improve my routing?
Here are my routes:
<Router>
<Route
path="/"
component={() =>
!auth ? <Redirect to="/login" /> : <Redirect to={path} />
}
/>
<Route exact path="/home" component={Home} />
<Route exact path="/dashboard" component={Dashboard} />
<Route exact path="/login" component={RedirectPage} />
</Router>
This is the full component:
import {
Route,
BrowserRouter as Router,
Link,
Redirect,
} from "react-router-dom";
import { Container, Button } from "#material-ui/core/";
import Login from "./Login";
import { useContext,useState } from "react";
import { UserContext } from "../App";
import { signOut } from "../Storage/Auth";
const Routes = () => {
const { auth, setAuth, logging } = useContext(UserContext);
const [path,setPath] = useState("/home")
const handleSignOut = () => {
signOut(setAuth);
console.log("Auth", auth);
};
const Home = () => {
console.log("Home");
return (
<Container>
<h1>Welcome</h1>
<Link to="/">
<Button onClick={handleSignOut}> Log Out</Button>
</Link>
<Link to="/dashboard">
<Button> Dash</Button>
</Link>
</Container>
);
};
const Dashboard = () => {
setPath("/dashboard")
console.log("Dash");
return (
<Container>
<Link to="/home">
<Button> HOME</Button>
</Link>
<h1>Dashboard</h1>
</Container>
);
};
const RedirectPage = () => {
if (!logging) {
return <div></div>;
} else {
return <Login />;
}
};
return (
<Router>
<Route
path="/"
component={() =>
!auth ? <Redirect to="/login" /> : <Redirect to={path} />
}
/>
<Route exact path="/home" component={Home} />
<Route exact path="/dashboard" component={Dashboard} />
<Route exact path="/login" component={RedirectPage} />
</Router>
);
};
export { Routes };
This is my Login component.
import { useState, useContext } from "react";
import {
Button,
Card,
Container,
Typography,
Box,
TextField,
} from "#material-ui/core/";
import { useHistory} from "react-router-dom";
import { signIn } from "../Storage/Auth";
import { UserContext } from "../App";
const Login = () => {
const [mail, setMail] = useState<string>("");
const [password, setPassword] = useState<string>("");
const { user, setUser } = useContext(UserContext);
const handleSignIn = async (m: string, p: string) => {
await signIn(m, p).then((e) => {
console.log("USERID", e, user);
setUser(e);
});
};
const history = useHistory();
const handleEnter = () => {
history.push("/home");
};
const handleOnKey = (e: any) => {
if (e.key === "Enter") {
e.preventDefault();
handleSignIn(mail, password);
handleEnter();
}
};
return (
<Card className="Card" raised={true}>
<Container className="Input">
<Typography className="Sign-in" paragraph={true} variant="inherit">
Sign in
</Typography>
<Box
className="Box"
borderColor="error.main"
border={2}
borderRadius="borderRadius"
>
<Container>
<TextField
fullWidth={true}
placeholder=" email"
value={mail}
onChange={(e) => {
setMail(e.target.value);
}}
onKeyDown={(e) => {
handleOnKey(e);
}}
/>
</Container>
</Box>
</Container>
<Container className="Input">
<Box
className="Box"
borderColor="error.main"
borderRadius="borderRadius"
border={2}
>
<Container>
<TextField
fullWidth={true}
placeholder=" password"
value={password}
onChange={(e) => {
setPassword(e.target.value);
}}
type="password"
onKeyDown={(e) => {
handleOnKey(e);
}}
/>
</Container>
</Box>
<h1> </h1>
<Button
onClick={() => {
handleSignIn(mail, password);
}}
fullWidth={true}
color="primary"
variant="contained"
type="submit"
>
Sign In{" "}
</Button>
<h1> </h1>
<Box className="Sign-in">
<Button size="small"> Register </Button>
</Box>
<h1> </h1>
</Container>
</Card>
);
};
export default Login;
This is the App component:
import { useEffect } from "react";
import { Routes } from "./Routing/Routes";
import "./App.css";
import { Container } from "#material-ui/core/";
import initFirebase from "./Storage/Secret";
import { useState, createContext } from "react";
import { onAuthChange } from "./Storage/Auth";
export const UserContext = createContext<any>(null);
function App() {
const [user, setUser] = useState(null);
const [auth, setAuth] = useState<string | null>("");
const [logging, setLogging] = useState(null)
useEffect(() => {
initFirebase();
}, []);
useEffect(() => {
onAuthChange(setAuth,setLogging);
}, [auth]);
return (
<UserContext.Provider value={{ user, setUser, auth,setAuth,logging }}>
<div className="App">
<Container>
<Routes />
</Container>
</div>
</UserContext.Provider>
);
}
export default App;
Also, here is the auth logic:
import firebase from "firebase/app";
import "firebase/auth";
const auth = () => firebase.auth();
const signIn = async (email, password) => {
await auth()
.signInWithEmailAndPassword(email, password)
.then((userCredential) => {
var user = userCredential.user;
console.log("USER", user);
return user.uid;
})
.catch((error) => {
var errorCode = error.code;
var errorMessage = error.message;
alert(errorCode, errorMessage);
return null;
});
};
const onAuthChange = (setState, setLoading) => {
auth().onAuthStateChanged((u) => {
if (!u) {
console.log(u);
setLoading(true);
} else {
setState(u);
setLoading(false);
}
});
};
const signOut = (setState) => {
auth()
.signOut()
.then(function () {
console.log("LOGGED OUT");
})
.catch(function (error) {
console.log("ERROR LOGGING OUT");
});
setState(null);
};
export { signIn, signOut, onAuthChange }
Finally, the full code is in https://gitlab.com/programandoconro/adminkanjicreator
Any suggestion will be appreciated, thanks.

I would recommend doing the auth check earlier. So something like this so that the routes themselves only get rendered if there is something in auth. I think your example is also missing the Switch statement which often helps.
<Router>
{!auth ? (
<Switch>
<Route exact path="/login" component={RedirectPage} />
</Switch>
) : (
<Switch>
<Route exact path="/home" component={Home} />
<Route exact path="/dashboard" component={Dashboard} />
</Switch>
)}
</Router>

Typically you will want some sort of "loading" or "indeterminant" state to represent neither authenticated nor unauthenticated. You can use this third "state" to hold the UI before committing to rendering one way or the other on anything based upon authentication.
Since your auth logic resolves to a boolean true|false.
const onAuthChange = (setState, setLoading) => {
auth().onAuthStateChanged((u) => {
if (!u) {
console.log(u);
setLoading(true);
} else {
setState(u);
setLoading(false);
}
});
};
You can use the fact that the initial auth state is neither of these. I suggest using null.
const [auth, setAuth] = useState<string | null>(null);
When rendering the Route utilizing the auth state you can augment the logic to return early before deciding to redirect.
<Route
path="/"
render={() => {
if (auth === null) return null;
return <Redirect to={auth ? path : "/login" />;
}}
/>
Note here that I've also switched over to the render prop, the component prop is intended for attaching actual React components. These are treated a little differently. You can read about the route render method differences here.
The full router example:
<Router>
<Switch>
<Route path="/home" component={Home} />
<Route path="/dashboard" component={Dashboard} />
<Route path="/login" component={RedirectPage} />
<Route
path="/"
render={() => {
if (auth === null) return null;
return <Redirect to={auth ? path : "/login" />;
}}
/>
</Switch>
</Router>
Note here that I've also included the Switch component and reordered the routes so the more specific paths are listed before less specific paths. This allows you to remove the unnecessary exact prop from all the routes since the Switch renders routes exclusively (versus inclusively as the Router does).

I finally managed to solve the issue. Now the reload works perfectly and the security was implemented as excepted. This is my final Router:
<Router>
<Route
path="/"
render={() =>
logging ? <Redirect to={"/login"} /> : <Redirect to={path} />
}
/>
<Route exact path="/" render={() => auth && <Home />} />
<Route exact path="/dashboard" render={() => auth && <Dashboard />} />
<Route exact path="/login" component={Login} />
</Router>
This is how the component looks like now.
import {
Route,
BrowserRouter as Router,
Link,
Redirect
} from "react-router-dom";
import { Container, Button } from "#material-ui/core/";
import Login from "./Login";
import { useContext, useState, useEffect } from "react";
import { UserContext } from "../App";
import { signOut } from "../Storage/Auth";
const Routes = () => {
const { auth, setAuth, logging } = useContext(UserContext);
const handleSignOut = () => {
signOut(setAuth);
console.log("Auth", auth);
};
const pathname = window.location.pathname;
const [path, setPath] = useState(pathname);
useEffect(() => {
console.log(path);
path === "/login" && setPath("/");
path !== "/" && path !== "/dashboard" && setPath("/");
}, [auth]);
const Home = () => {
console.log("Home");
return (
<Container>
<h1>Welcome</h1>
<Link to="/">
<Button onClick={handleSignOut}> Log Out</Button>
</Link>
<Link to="/dashboard">
<Button> Dash</Button>
</Link>
</Container>
);
};
const Dashboard = () => {
console.log("Dash");
return (
<Container>
<Link to="/">
<Button> HOME</Button>
</Link>
<h1>Dashboard</h1>
</Container>
);
};
return (
<Router>
<Route
path="/"
render={() =>
logging ? <Redirect to={"/login"} /> : <Redirect to={path} />
}
/>
<Route exact path="/" render={() => auth && <Home />} />
<Route exact path="/dashboard" render={() => auth && <Dashboard />} />
<Route exact path="/login" component={Login} />
</Router>
);
};
export { Routes };
Thanks #Richard and #Drew for their kind support.

Related

Accessing url only with valid token

I'm using React and firebase, where I have an admin, and there I generate a token, which I can already register in the database. So I wanted to copy this generated url, for example: localhost:5173/avaliacao/a57078f588e, where a57078f588e is the generated token id for each survey
So the user would access the Rating page only if this token is valid, otherwise it would go to a 404 page.
I'm trying, however everything I try the undefined token.
Here is my App.jsx
export function App() {
return (
<Router>
<Routes>
<Route element={<PrivateRoutes />}>
<Route element={<Admin />} path="/admin" />
<Route element={<Dashboard />} path="/dashboard" />
<Route element={<Collaborator />} path="/collaborators" />
<Route element={<Service />} path="/services" />
</Route>
<Route para element={<TokenRoutes />}>
<Route element={<Rating />} path="/avaliacao/:token" />
<Route element={<Thanks />} path="/thanks" />
<Route element={<NotFound />} path="*" />
</Route>
<Route element={<Login />} path="/" />
</Routes>
</Router>
);
}
And here is my TokenRoutes:
import { Navigate, Outlet } from "react-router-dom";
import { useToken } from "../hooks/useToken";
export function TokenRoutes() {
const { token } = useToken();
console.log(token);
return token != "undefined" ? <Outlet /> : <Navigate to="/notfound" />;
}
And my Rating page:
export function Rating() {
const { token } = useToken();
console.log(token);
let { id } = useParams();
return (
<div className="containerRating">
<span className="login100-form-title p-b-48">
<i className="zmdi zmdi-font"></i>
<img src={imgLogo} alt="Imagem" />
</span>
Param: {id}
<Form />
</div>
);
}
My useToken:
import { addDoc, collection, getDocs } from "firebase/firestore";
import { createContext, useContext, useEffect, useState } from "react";
import { toast } from "react-toastify";
import { uid } from "uid";
import { db } from "../services/firebaseConfig";
const TokenContext = createContext();
export function TokenProvider({ children }) {
const [tokens, setTokens] = useState([]);
const [token, setToken] = useState();
const tokensCollectionRef = collection(db, "tokens");
useEffect(() => {
const getTokens = async () => {
const data = await getDocs(tokensCollectionRef);
setTokens(
data.docs.map((doc) => ({
...doc.data(),
}))
);
};
getTokens();
}, []);
async function generateToken() {
await addDoc(tokensCollectionRef, {
id: uid(),
createdAt: new Date().toString(),
expiredIn: new Date(
new Date().setDate(new Date().getDate() + 7)
).toString(),
used: false,
})
.then(() => {
toast.success("Avaliação gerada com sucesso!", {
theme: "colored",
});
console.log("Gerado no firebase 🔥");
})
.catch((error) => {
toast.error("Ocorreu um erro ao gerar", {
theme: "colored",
});
console.log(error.message);
});
}
return (
<TokenContext.Provider value={{ generateToken, token, tokens }}>
{children}
</TokenContext.Provider>
);
}
export function useToken() {
const context = useContext(TokenContext);
return context;
}
In order not to put all the code here, any other doubt, follow the complete code on github:
https://github.com/eltonsantos/evaluation-system-react
Resuming:
I just want to get the URL generated by me containing the token, share it with the user and the user was able to access it, but if he changes the url it gives a 404 page. url that I shared the token comes undefined

How to create Private Routes with firebase v9 reactjs [duplicate]

This question already has an answer here:
React-Router-Dom unable to render page but routes back due to PrivateRoute
(1 answer)
Closed 8 months ago.
My problem is that the moment i navigate to the homepage and the user is not authenticated the page shows for a split second and then move on to the login page. I want it to redirect to login only and not show the homepage for a split second
I already created a private route in my project but for a split second the protected routes shows when i navigate on to it.
here is my code:
AuthContextProvider
const AuthProvider = ({ children }) => {
const [user, setUser] = useState(null);
useEffect(() => {
const unsubscribe = onAuthStateChanged(auth, (currentUser) => {
setUser(currentUser);
});
return () => unsubscribe();
}, []);
const value = { user };
return <AuthContext.Provider value={value}>{children}</AuthContext.Provider>;
};
PrivateRoute.js
const PrivateRoute = ({ children }) => {
let { user } = useAuth();
if (user) {
return <Outlet />;
} else {
return <Navigate to="/login" />;
}
};
App.js
function App() {
return (
<Routes>
<Route path="/login" element={<LoginPage />} />
<Route path="/" element={<Layout />}>
<Route element={<PrivateRoute />}>
<Route path="/" element={<Home />} />
<Route path="/home" element={<Home />} />
<Route path="/reminders" element={<Reminders />} />
<Route path="/archive" element={<Archive />} />
<Route path="/trash" element={<Trash />} />
</Route>
</Route>
</Routes>
);
}
Loginpage.js
const LoginPage = () => {
const { user } = useAuth();
const navigate = useNavigate();
const signIn = async () => {
const provider = new GoogleAuthProvider();
await signInWithRedirect(auth, provider);
};
useEffect(() => {
onAuthStateChanged(auth, (currentUser) => {
if (currentUser) {
navigate("/");
}
});
}, []);
return (
<>
<button
onClick={signIn}
className="bg-blue-500 p-3 text-white hover:bg-blue-600"
>
Sign In With Google
</button>
</>
);
};
Code for hindering the Loggedin User to go to the Login Route
I have created a SpecialRoute which will redirect the loggedIn User to the mainpage if the user tries to go the login page.
SpecialRoute.js
import { Login } from '../pages/Login';
import { useAuth } from '../firebase-config';
import React from 'react';
import { Outlet, Navigate } from 'react-router-dom';
// import { useAuth } from '../firebase-config';
export const SpecialRoute = () => {
const user = useAuth();
return user ? <Outlet /> : <Navigate to="/" replace />;
};
App.js
<Route element={<SpecialRoute />}>
<Route path="/login" element={<Login />} />
</Route>
In your Private Route Component, do this :-
const PrivateRoute = ({ children }) => {
let { user } = useAuth();
return typeof user === 'undefined' ? (
<h1>Loading.....</h1>
) : user ? (
<Outlet />
) : (
<Navigate to="/login" />
);
};
Below is how I created my private routes (in Firebase v9):-
useAuth Hook
// custom hook
export function useAuth() {
//
const [currentUser, setCurrentUser] = useState<any>();
useEffect(() => {
const unSubscribe = onAuthStateChanged(auth, (user) =>
setCurrentUser(user)
);
return unSubscribe;
}, []);
return currentUser;
}
My PrivateRoute/ProtectedRouted Component
import { Login } from '../pages/Login';
import React from 'react';
import { Outlet } from 'react-router-dom';
import { useAuth } from '../firebase-config';
export const ProtectedRoute = () => {
const user = useAuth();
console.log('/////user autheticated', user);
return typeof user === 'undefined' ? (
<h1>Loading.....</h1>
) : user ? (
<Outlet />
) : (
<Login />
);
};
App.js
function App() {
return (
<>
<Router>
<Routes>
<Route element={<ProtectedRoute />}>
<Route path="/" element={<Home />} />
</Route>
<Route path="/login" element={<Login />} />
<Route path="/signup" element={<Signin />} />
</Routes>
</Router>
</>
);
}

React router renders the invalid component then renders valid component

Whenever I go the the path ("/") even if I am logged in, Signup component is loaded once for few second then Dashboard is shown same happens with redirecting how to solve it.
<Route
exact
path="/"
render={() => {
return loggedIn ? <Dashboard /> : <Signup />;
}}
/>
<Route
exact
path="/resetPassword"
render={() => {
return loggedIn ? (
<Redirect to="/" />
) : (
<ResetPassword/>
);
}}
/>
and I'm setting the login like this:
const cookieCheck = () => {
const mt = Cookies.get("rt");
if (mt === "" || mt === undefined) {
if (loggedIn) {
setLogin(false);
}
} else {
if (!loggedIn) {
setLoggedIn(true);
}
}
};
My complete code is as follows
import React, { Fragment, useState, useEffect, lazy, Suspense } from 'react';
import { Paper } from '#material-ui/core';
import Dashboard from './Components/Dashboard/Dashboard';
import LoadingPage from './Components/LoadingPage/main';
import ForgotPassword from './Components/ForgotPassword/Fp';
import Signup from './Components/Signup/Signup';
import Login from './Components/Login/Login';
import PageNotFound from './Components/404/Page.js';
import Activation from './Components/Activation/Activation';
import ResetPassword from './Components/ResetPassword/Reset';
import {
BrowserRouter as Router,
Route,
Switch,
Redirect,
} from 'react-router-dom';
import Cookies from 'js-cookie';
const App = () => {
const [login, setLogin] = useState(false);
const checkStatus = function () {
const mt = Cookies.get('t');
if (mt === '' || mt === undefined) {
setLogin(false);
} else {
setLogin(true);
// return true;
}
};
useEffect(() => {
const interval = setInterval(() => {
cookieCheck();
}, 1000);
return () => clearInterval(interval);
});
const cookieCheck = async () => {
const mt = await Cookies.get('rt');
if (mt === '' || mt === undefined) {
if (login) {
setLogin(false);
}
} else {
if (!login) {
setLogin(true);
}
}
};
console.log(login);
return (
<Router>
<Fragment>
<Paper elevation={0}>
<Switch>
<Route
path="/forgotpassword"
exact
component={ForgotPassword}
/>
<Route
exact
path="/login"
render={() => {
return login ? <Redirect to="/" /> : <Login />;
}}
/>
<Route
exact
path="/signup"
render={() => {
if (login) {
return <Redirect to="/" />;
} else {
return <Signup />;
}
}}
/>
<Route
exact
path="/"
render={() => {
return login ? (
<Dashboard />
) : (
<LoadingPage />
);
}}
/>
<Route
exact
path="/resetPassword/:code/:uid"
render={() => {
return login ? (
<Redirect to="/" />
) : (
ResetPassword
);
}}
/>
<Route
exact
path="/activation/:code/:uid"
component={Activation}
/>
<Route component={PageNotFound} />
</Switch>
</Paper>
</Fragment>
</Router>
);
};
export default App;
You need try something like this to add loading state to your component:
import React, { Fragment, useState, useEffect, lazy, Suspense } from "react";
import { Paper } from "#material-ui/core";
import Dashboard from "./Components/Dashboard/Dashboard";
import LoadingPage from "./Components/LoadingPage/main";
import ForgotPassword from "./Components/ForgotPassword/Fp";
import Signup from "./Components/Signup/Signup";
import Login from "./Components/Login/Login";
import PageNotFound from "./Components/404/Page.js";
import Activation from "./Components/Activation/Activation";
import ResetPassword from "./Components/ResetPassword/Reset";
import {
BrowserRouter as Router,
Route,
Switch,
Redirect,
} from "react-router-dom";
import Cookies from "js-cookie";
const App = () => {
const [login, setLogin] = useState(false);
const [loading, setLoading] = useState(true);
const checkStatus = function () {
const mt = Cookies.get("t");
if (mt === "" || mt === undefined) {
setLogin(false);
} else {
setLogin(true);
}
setLoading(false);
};
useEffect(() => {
const interval = setInterval(() => {
checkStatus();
}, 1000);
return () => clearInterval(interval);
}, []);
console.log(login);
const isLoginComponent = login ? <Dashboard /> : <LoadingPage />;
return (
<Router>
<Fragment>
<Paper elevation={0}>
<Switch>
<Route path="/forgotpassword" exact component={ForgotPassword} />
<Route
exact
path="/login"
render={() => {
return login ? <Redirect to="/" /> : <Login />;
}}
/>
<Route
exact
path="/signup"
render={() => {
if (login) {
return <Redirect to="/" />;
} else {
return <Signup />;
}
}}
/>
<Route
exact
path="/"
render={() => {
return loading ? <div>loading</div> : isLoginComponent;
}}
/>
<Route
exact
path="/resetPassword/:code/:uid"
render={() => {
return login ? <Redirect to="/" /> : ResetPassword;
}}
/>
<Route exact path="/activation/:code/:uid" component={Activation} />
<Route component={PageNotFound} />
</Switch>
</Paper>
</Fragment>
</Router>
);
};
export default App;
Read more about how cookies work here: https://developer.mozilla.org/en-US/docs/Mozilla/Add-ons/WebExtensions/API/cookies/get
I think this issue is you don't immediately check the cookie status when the component mounts. This coupled with login initial state false will render any login ? true : false false branch component until the first cookie check that returns valid authentication.
const [login, setLogin] = useState(false);
const checkStatus = function () {
const mt = Cookies.get('t');
if (mt === '' || mt === undefined) {
setLogin(false);
} else {
setLogin(true);
}
};
useEffect(() => {
const interval = setInterval(() => {
checkStatus(); // <-- not called for 1000ms
}, 1000);
return () => clearInterval(interval);
});
Solution
Need to also immediately invoke the cookie check function. I suggest also starting with a non-true/false state value so you know when the initial check is complete.
const [login, setLogin] = useState(null);
const checkStatus = function () {
const mt = Cookies.get('t');
if (mt === '' || mt === undefined) {
setLogin(false);
} else {
setLogin(true);
}
};
useEffect(() => {
const interval = setInterval(() => {
checkStatus();
}, 1000);
checkStatus(); // <-- also invoke first render
return () => clearInterval(interval);
});
Check for login === null and return null (or any pending/loading UI really), otherwise return the regular ternary.
<Route
exact
path="/"
render={() => {
if (login === null) return null;
return login ? (
<Dashboard />
) : (
<LoadingPage />
);
}}
/>

history.push not working react router dom

Hello guys I have a problem with useHistory(); (react-router-dom);
my history.push is not working, I need to refresh the browser for him work.
I am new with react and,
what I am doing wrong?
Can anyone help me with it??
sx
code below:
const history = useHistory();
const handleSignIn = useCallback(
async data => {
try {
await getToken(data.username, data.password);
history.push('/dashboard');
} catch (err) {
if (err instanceof Yup.ValidationError) {
const errors = getValidationErrors(err);
if (formRef.current) {
formRef.current.setErrors(errors);
}
}
}
},
[getToken, history],
);
return (
<Container>
<Content>
<h1>Faça seu login</h1>
<Form ref={formRef} onSubmit={handleSignIn}>
<Input name="username" placeholder="Usuário" />
<Input name="password" type="password" placeholder="Senha" />
<Button type="submit">Entrar</Button>
</Form>
index of routes below :
import React from 'react';
import { Switch } from 'react-router-dom';
import Route from './Route';
import Register from '../pages/Register';
import SignIn from '../pages/SignIn';
import SignUp from '../pages/SignUp';
import Dashboard from '../pages/Dashboard';
export default function Routes() {
return (
<Switch>
<Route path="/" exact component={SignIn} />
<Route path="/signup" component={SignUp} />
<Route path="/register" component={Register} />
<Route path="/dashboard" component={Dashboard} isPrivate />
</Switch>
);
}
this is my code of private routes:
export default function Route({
isPrivate = false,
component: Component,
...rest
}) {
const { user } = useAuth();
return (
<ReactDOMRoute
{...rest}
render={({ location }) => {
return isPrivate === !!user ? (
<Component />
) : (
<Redirect
to={{
pathname: isPrivate ? '/' : '/dashboard',
state: { from: location },
}}
/>
);
}}
/>
);
}
My App.js below:
import Routes from './routes';
export default function App() {
return (
<BrowserRouter>
<AppProvider>
<Routes />
</AppProvider>
<GlobalStyle />
</BrowserRouter>
);
}

react router "# sign inside route"

i using react-router for my project,
in that there's a problem which is for every route "#" sign is added at the start of every router path..
ex": http://localhost:3000/#/login
i want to remove that # sign but i couldn't able solve it my self.
procedure of my routing is
in app.js im checking the user is signed in or not if not signed in then he will redirect into /login page.(for that also it is showing path as http://localhost:3000/#/login)
below is the app.js
import React, { Component, Fragment } from "react";
import { HashRouter, Route, Switch, Redirect } from "react-router-dom";
// import { renderRoutes } from 'react-router-config';
import "./App.scss";
import { connect } from "react-redux";
import { loadUser } from "./actions/authActions";
const loading = () => (
<div className="animated fadeIn pt-3 text-center">Loading....</div>
);
// Containers
const DefaultLayout = React.lazy(() =>
import("./containers/DefaultLayout/DefaultLayout")
);
// Pages
const Login = React.lazy(() => import("./views/Login/Login"));
const Register = React.lazy(() => import("./views/Register/Register"));
const Page404 = React.lazy(() => import("./views/Page404/Page404"));
const Page500 = React.lazy(() => import("./views/Page500/Page500"));
class App extends Component {
componentDidMount() {
this.props.LOADUSER();
}
render() {
return (
<HashRouter>
<React.Suspense fallback={loading()}>
<Switch>
{!this.props.isAuthenicated ? (
<Fragment>
<Redirect from="*" to="/login" />
<Route
exact
path="/login"
name="Login Page"
render={props => <Login {...props} />}
/>
{/* <Route
exact
path="/register"
name="Register Page"
render={(props) => <Register {...props} />}
/>
<Route
exact
path="/404"
name="Page 404"
render={(props) => <Page404 {...props} />}
/>
<Route
exact
path="/500"
name="Page 500"
render={(props) => <Page500 {...props} />}
/> */}
</Fragment>
) : (
<Route
name="Home"
path="/"
render={props => <DefaultLayout {...props} />}
/>
)}
</Switch>
</React.Suspense>
</HashRouter>
);
}
}
const mapStateToProps = state => ({
isAuthenicated: state.auth.isAuthenicated,
isLoading: state.auth.isLoading,
error: state.error,
token: state.auth.token
});
const mapDispachToProps = dispach => {
return {
//LOGIN: (newUser) => dispach(login(newUser)),
LOADUSER: () => dispach(loadUser())
};
};
export default connect(mapStateToProps, mapDispachToProps)(App);
else he is signed in then im using a component called DefaultLayout Component I will render it.
it has all the routes for other usages which is using routes from routes.js.
below is the DefaultLayout Component
import React, { Component, Suspense } from "react";
import { Redirect, Route, Switch } from "react-router-dom";
import * as router from "react-router-dom";
import { Container } from "reactstrap";
import { logout } from "../../actions/authActions";
import { ToastContainer } from "react-toastify";
import Loader from "react-loaders";
import "react-toastify/dist/ReactToastify.css";
import {
AppHeader,
AppSidebar,
AppSidebarFooter,
AppSidebarForm,
AppSidebarHeader,
AppSidebarMinimizer,
AppBreadcrumb2 as AppBreadcrumb,
AppSidebarNav2 as AppSidebarNav
} from "#coreui/react";
// sidebar nav config
import _navs from "../../_nav";
// routes config
import routes from "../../routes";
import { connect } from "react-redux";
const DefaultHeader = React.lazy(() => import("./DefaultHeader"));
class DefaultLayout extends Component {
state = {
isAuthenicated: true
};
loading = () => <Loader type="ball-triangle-path" />;
signOut(e) {
e.preventDefault();
this.props.history.push("/login");
this.props.LOGOUT();
}
render() {
return (
<div className="app">
<AppHeader fixed>
<Suspense fallback={this.loading()}>
<DefaultHeader onLogout={e => this.signOut(e)} />
</Suspense>
</AppHeader>
<div className="app-body">
<AppSidebar fixed display="lg">
<AppSidebarHeader />
<AppSidebarForm />
<Suspense>
<AppSidebarNav
navConfig={_navs}
{...this.props}
router={router}
/>
</Suspense>
<AppSidebarFooter />
<AppSidebarMinimizer />
</AppSidebar>
<main className="main">
<AppBreadcrumb appRoutes={routes} router={router} />
<Container fluid>
<Suspense fallback={this.loading()}>
<Switch>
{routes.map((route, idx) => {
return route.component ? (
<Route
key={idx}
path={route.path}
exact={route.exact}
name={route.name}
render={props => (
<route.component {...props} {...route.props} />
)}
/>
) : null;
// (
// <Redirect from="*" to="/dashboard" />
// );
})}
<Redirect from="*" to="/" />
</Switch>
</Suspense>
<ToastContainer autoClose={3000} position="bottom-center" />
</Container>
</main>
</div>
</div>
);
}
}
const mapStateToProps = state => ({
isAuthenicated: state.auth.isAuthenicated,
error: state.error
});
const mapDispachToProps = dispach => {
return {
LOGOUT: () => dispach(logout())
};
};
export default connect(mapStateToProps, mapDispachToProps)(DefaultLayout);
example of routes.js also below
const routes =[{
path: "/",
exact: true,
name: "Home",
component: Dashboard
},
{
path: "/user_overview",
name: "Users Overview",
component: Register
}]
for every route it's showing # can anyone help me to resolve that # sign in the route path?
Thank you!
You are using HashRouter this is the purpose of this Router.
Usually one uses it in-order to prevent the server to get those routes.
If you want to use real routes just replace it with BrowserRouter.
Pay attention that your server will need to be able to support those routes.
navigate to some route say /some/page press reload, make sure that your server return your client code.

Resources