Facing issue with Custom Route with latest react-router-dom version 6 - javascript

Recently, I am facing issue with Custom Route with latest react-router-dom version 6 in my code.
I have created custom route for authorized if user is not login then it will redirect to sign in page. It was working with previous react router version but now it's got broke with latest one.
I am posting the code below.
Getting below error message as well.
[UserRoute] is not a component. All component children of must be a Route or <React.Fragment>
LoadingToRedirect.js
import React, { useState, useEffect } from "react";
import { useNavigate } from "react-router-dom";
const LoadingToRedirect = () => {
const [count, setCount] = useState(5);
const navigate = useNavigate();
useEffect(() => {
const interval = setInterval(() => {
setCount((currentCount) => --currentCount);
}, 1000);
count === 0 && navigate("/login");
return () => clearInterval(interval);
}, [count, navigate]);
return (
<div>
<p>Redirecting you in {count} seconds</p>
</div>
);
};
export default LoadingToRedirect;
UserRoute.js
import React from "react";
import { Route, Routes } from "react-router-dom";
import { useSelector } from "react-redux";
import LoadingToRedirect from "./LoadingToRedirect";
const UserRoute = ({ children, ...rest }) => {
const { currentUser } = useSelector((state) => state.user);
return currentUser ? <Route {...rest} /> : <LoadingToRedirect />;
};
export default UserRoute;
App.js
import React, { useEffect, Fragment } from "react";
import "./App.css";
import { BrowserRouter, Routes, Route } from "react-router-dom";
import Home from "./pages/Home";
import Login from "./pages/Login";
import Register from "./pages/Register";
import UserRoute from "./components/UserRoute";
import { useDispatch } from "react-redux";
import { auth } from "./firebase";
import { setUser } from "./redux/actions";
import Header from "./components/Header";
import AddEdit from "./pages/AddEdit";
function App() {
const dispatch = useDispatch();
useEffect(() => {
auth.onAuthStateChanged((authUser) => {
if (authUser) {
dispatch(setUser(authUser));
} else {
dispatch(setUser(null));
}
});
}, [dispatch]);
return (
<BrowserRouter>
<div className="App">
<Header />
<ToastContainer position="top-center" />
<Fragment>
<Routes>
<UserRoute path="/" element={<Home />} />
<Route path="/login" element={<Login />} />
<Route path="/register" element={<Register />} />
<UserRoute path="/addContact" element={<AddEdit />} />
</Routes>
</Fragment>
</div>
</BrowserRouter>
);
}
export default App;

In react-router v6, the Routes component allows only Route children.
In UserRoute.js if there's no user you are returning LoadingToRedirect:
return currentUser ? <Route {...rest} /> : <LoadingToRedirect />;
You can try changing this to:
const UserRoute = ({ children, path, element }) => {
const { currentUser } = useSelector((state) => state.user);
return <Route path={path} element={ currentUser ? element : <LoadingToRedirect />} />;
};

Related

An unauthenticated user can still see the "/account" page

An unauthenticated user can still see the "/account" page for a few seconds I mean there is still a delay of a few seconds before the unauthenticated user is completely redirected to another page. even though I have used ProtectedRoute, how can I make unauthenticated users unable to see the "/account" page at all without delay? i use react-router-dom 6.6.1 and firebase auth
here is for the app.js
import { ThemeProvider } from '#mui/material/styles';
import React from 'react';
import { BrowserRouter as Router, Route, Routes, Navigate} from 'react-router-dom'
import Home from './components/Home'
import Account from './components/Account';
import Signin from './components/Home/Signin';
import theme from './theme';
import { AuthContextProvider } from './components/Context/AuthContext';
import ProtectedRoute from './components/ProtectedRoute';
function App() {
return (
<ThemeProvider theme={theme}>
<AuthContextProvider>
<Router>
<Routes>
<Route path='/' element={<Home />} />
<Route path='/signin' element={<Signin />} />
<Route path='/account' element={<ProtectedRoute><Account /></ProtectedRoute>} />
</Routes>
</Router>
</AuthContextProvider>
</ThemeProvider>
)
}
export default App
and this is for the ProtectedRoute.js
import React from 'react';
import { Navigate } from 'react-router-dom';
import { UserAuth } from './Context/AuthContext';
const ProtectedRoute = ({ children }) => {
const { user } = UserAuth();
if (!user) {
return <Navigate to='/' />;
}
return children;
};
export default ProtectedRoute;
this if for the UserAuth :
import { createContext, useContext, useEffect, useState } from 'react';
import {
createUserWithEmailAndPassword,
signInWithEmailAndPassword,
onAuthStateChanged,
} from 'firebase/auth';
import { auth } from '../../firebase';
const UserContext = createContext();
export const AuthContextProvider = ({ children }) => {
const [user, setUser] = useState({});
const createUser = (email, password) => {
return createUserWithEmailAndPassword(auth, email, password);
};
const signIn = (email, password) => {
return signInWithEmailAndPassword(auth, email, password)
}
useEffect(() => {
const unsubscribe = onAuthStateChanged(auth, (currentUser) => {
setUser(currentUser);
});
return () => {
unsubscribe();
};
}, []);
return (
<UserContext.Provider value={{ createUser, user, signIn }}>
{children}
</UserContext.Provider>
);
};
export const UserAuth = () => {
return useContext(UserContext);
};
I want to redirect unauthenticated users to the main page without delay
it’s probably due to the fact that your guard is validating off of !user however your initial auth state has user as {}. In this case an empty object will validate as truthy.
You could either set the initial state of user as null or you could update th guard validation to check for a value on user like if (!user.id) …
Render Protected and Base routes conditional so unauthenticated user never have access of Protected routes.
Use the following code.
Always make separate file for routing for better code readability and Separation of concerns.
BaseRoutes.js
import React from 'react'
import { Route } from 'react-router-dom'
import Home from './components/Home'
import Signin from './components/Home/Signin';
const BaseRoutes = (
<>
<Route path='/' element={<Home />} />
<Route path='/signin' element={<Signin />} />
</>
)
export default BaseRoutes
ProtectedRoutes.js
import React from 'react';
import { Route } from 'react-router-dom';
import Account from './components/Account';
const ProtectedRoutes = () => {
return (
<>
<Route path='/account' element={<Account />} />
</>
)
};
export default ProtectedRoutes;
Routes.js
import React from 'react'
import { Navigate, Route, Routes, BrowserRouter } from 'react-router-dom'
import { UserAuth } from './Context/AuthContext';
import ProtectedRoutes from './components/ProtectedRoutes';
import BaseRoutes from './components/BaseRoutes';
const Router = () => {
const { user } = UserAuth();
const isUser = Boolean(user)
const redirectUrl = isUser ? '/account' : '/signin'
return (
<BrowserRouter>
<Routes>
{isUser ? <BaseRoutes /> : <ProtectedRoutes />}
<Route
path="*"
element={<Navigate to={redirectUrl} />}
/>
</Routes>
</BrowserRouter>
)
}
export default Router
app.js
import React from 'react';
import { AuthContextProvider } from './components/Context/AuthContext';
import { ThemeProvider } from '#mui/material/styles';
import theme from './theme';
import Router from './routes'
function App() {
return (
<ThemeProvider theme={theme}>
<AuthContextProvider>
<Router />
</AuthContextProvider>
</ThemeProvider>
)
}
export default App

check authenticated user in ProtectedRouter component in react using react router v6

my app.jsx
import axios from "axios";
import { createContext, useState } from "react";
import { BrowserRouter, Routes, Route } from "react-router-dom";
import NavBar from "./components/Navbar";
import ProtectedRoute from "./components/ProtectedRoute";
import Home from "./pages/Home";
import Login from "./pages/Login";
import MyBlogs from "./pages/MyBlogs";
import Profile from "./pages/Profile";
import Signup from "./pages/Signup";
export const AuthContext = createContext();
const App = () => {
const [loggedIn, setLoggedIn] = useState(
Boolean(sessionStorage.getItem("loggedIn"))
);
const VUserData = sessionStorage.getItem("userData");
const [userData, setUserData] = useState(
VUserData ? JSON.parse(VUserData) : null
);
function getUserData() {
return axios
.get("/api/user")
.then((res) => {
return Promise.resolve(res.data);
})
.catch((err) => {
return Promise.reject(err.response);
});
}
return (
<BrowserRouter>
<AuthContext.Provider
value={{
loggedIn,
setLoggedIn,
userData,
setUserData,
getUserData,
}}
>
<Routes>
<Route path="/" element={<NavBar />}>
<Route index element={<Home />} />
<Route path="login" element={<Login />} />
<Route path="signup" element={<Signup />} />
<Route
path="profile"
element={
<ProtectedRoute>
<Profile />
</ProtectedRoute>
}
/>
<Route
path="my-blogs"
element={
<ProtectedRoute>
<MyBlogs />
</ProtectedRoute>
}
/>
</Route>
</Routes>
</AuthContext.Provider>
</BrowserRouter>
);
};
export default App;
my ProtectedRoute.jsx
import { useContext } from "react";
import { Navigate, useLocation } from "react-router-dom";
import { AuthContext } from "../app";
const ProtectedRoute = ({ children, ...rest }) => {
const { loggedIn, getUserData } = useContext(AuthContext);
const location = useLocation();
if (loggedIn) {
getUserData()
.then((res) => {
return children;
})
.catch((res) => {
return (
<Navigate
to="/login"
replace
state={{ path: location.pathname }}
/>
);
});
} else {
return (
<Navigate to="/login" replace state={{ path: location.pathname }} />
);
}
};
export default ProtectedRoute;
my home.jsx
import React from "react";
import { Outlet } from "react-router-dom";
import NavBar from "../components/Navbar";
const Home = () => {
return (
<React.Fragment>
<NavBar />
<Outlet />
</React.Fragment>
);
};
export default Home;
My problem is after successful login, the profile page not rendering. It's just a blank white page but if I replacegetUserData() and the whole promise resolve with just return children; it's in ProtectedRoute.jsx it's working fine why is that?
how could I check whether the user is logged or not by requesting to the backend in ProtectedRoute.jsx

Default route always execute in react router

I am working on a project where I am using the strikingDash template. Here I face some issues of routing while changing the routes from URL.
auth.js
import React, { lazy, Suspense } from "react"
import { Spin } from "antd"
import { Switch, Route, Redirect } from "react-router-dom"
import AuthLayout from "../container/profile/authentication/Index"
const Login = lazy(() =>
import("../container/profile/authentication/overview/SignIn")
)
const SignUp = lazy(() =>
import("../container/profile/authentication/overview/SignUp")
)
const ForgetPassword = lazy(() =>
import("../container/profile/authentication/overview/ForgetPassword")
)
const EmailConfirmation = lazy(() =>
import("../container/profile/authentication/overview/EmailConfirmation")
)
const VerificationPage = lazy(() =>
import("../container/profile/authentication/overview/VerificationPage")
)
const NotFound = () => {
console.log("NOT FOUND")
return <Redirect to="/" />
}
const FrontendRoutes = () => {
return (
<Switch>
<Suspense
fallback={
<div className="spin">
<Spin />
</div>
}
>
<Route exact path="/verification" component={VerificationPage} />
<Route exact path="/email-confirmation" component={EmailConfirmation} />
<Route exact path="/forgetPassword" component={ForgetPassword} />
<Route exact path="/signup" component={SignUp} />
<Route exact path="/" component={Login} />
<Route component={NotFound} />
</Suspense>
</Switch>
)
}
export default AuthLayout(FrontendRoutes)
App.js
import React, { useEffect, useState } from "react";
import { hot } from "react-hot-loader/root";
import { Provider, useSelector } from "react-redux";
import { ThemeProvider } from "styled-components";
import { BrowserRouter as Router, Redirect, Route } from "react-router-dom";
import { ConfigProvider } from "antd";
import store from "./redux/store";
import Admin from "./routes/admin";
import Auth from "./routes/auth";
import "./static/css/style.css";
import config from "./config/config";
import ProtectedRoute from "./components/utilities/protectedRoute";
const { theme } = config;
const ProviderConfig = () => {
const { rtl, isLoggedIn, topMenu, darkMode } = useSelector(state => {
return {
darkMode: state.ChangeLayoutMode.data,
rtl: state.ChangeLayoutMode.rtlData,
topMenu: state.ChangeLayoutMode.topMenu,
isLoggedIn: state.Authentication.login,
};
});
const [path, setPath] = useState(window.location.pathname);
useEffect(() => {
let unmounted = false;
if (!unmounted) {
setPath(window.location.pathname);
}
// eslint-disable-next-line no-return-assign
return () => (unmounted = true);
}, [setPath]);
return (
<ConfigProvider direction={rtl ? "rtl" : "ltr"}>
<ThemeProvider theme={{ ...theme, rtl, topMenu, darkMode }}>
<Router basename={process.env.PUBLIC_URL}>
{!isLoggedIn ? <>{console.log("INSIDE PUBLIC")}<Route path="/" component={Auth} /></> : <ProtectedRoute path="/admin" component={Admin} />}
{isLoggedIn && (path === process.env.PUBLIC_URL || path === `${process.env.PUBLIC_URL}/`) && (
<Redirect to="/admin" />
)}
</Router>
</ThemeProvider>
</ConfigProvider>
);
};
function App() {
return (
<Provider store={store}>
<ProviderConfig />
</Provider>
);
}
export default hot(App);
Whenever I change the URL to another route as I described above in Frontend Routes. Then it will always print console statements like these:
INSIDE PUBLIC
NOT FOUND
INSIDE PUBLIC
NOT FOUND
Expected Behaviour: Whenever I update the URL it will render the component according to the switch case and return it back
Actual Behaviour: Whenever I update the URL it will render the component as well as the default component. I think Switch here renders multiple components, but I don't know why.
I just resolved the issue by moving the Switch Tag inside the Suspense tag in the auth.js file.
The problem should be in the order of your pages: the root path works as a collector of all the pages, you should try to add the exact keyword to the Router path. Here the reference for the differences between the different notations.
<Route exact path="/" component={Login} />

ReactJS: Global Okta Auth Helper Function

I have my React web app authenticated using Okta however if the user is not authenticated or the token expires then it will redirect the user to the /login page.
Page1.js:
import React, { useState, useEffect } from "react";
import { useOktaAuth } from "#okta/okta-react";
import { Redirect, useHistory } from "react-router-dom";
const { authState } = useOktaAuth();
const history = useHistory();
useEffect(() => {
if (!authState) {
history.push("/login");
}
});
Is there a way I can include the above into an function that I can import to each different Page[#].js instead of including the above code in each file?
Just trying to refactor and make sure my code is tidy as I go but unsure the best way to tackle this.
TIA!
You can wrap all the components that required users to be logged in inside a component and protect the routes.
Once the user logs in, set a token in localstorage or redux (you need to persist it). Specify the route to go through IsloggedIn component so that, those routes will only be accessible if user is logged in, else will be redirected to the login page
Example
import React from "react";
import { Redirect, Route } from "react-router-dom";
function IsLoggedIn({ Component, ...props }) {
const isAuthenticated = localStorage.getItem("isAuthenticated");
return (
<Route {...props}
render={(props) =>
isAuthenticated ? <Component {...props} /> : <Redirect to="/login" />
}
/>
);
}
export default IsLoggedIn;
In App.js
function App(){
return(
<BrowserRouter>
<Route exact path="/login" component={Login} />
<IsLoggedIn exact path="/" component={Page1} />
</BrowserRouter>
)
}
you can use the below
private-route component
import React, { useEffect } from 'react';
import { Route, Redirect, RouteProps, useHistory } from 'react-router-dom';
import { useAppDispatch, useAppSelector } from 'app/config/store';
import { SecureRoute, useOktaAuth } from '#okta/okta-react';
import { authenticationSuccess } from '../reducers/authentication-slice';
export const PrivateRouteComponent = ({ component: Component, ...rest }: IOwnProps) => {
//reducer
const isAuthenticated = useAppSelector(state => state.authentication.isOktaAuthenticated);
const { authState, oktaAuth } = useOktaAuth();
const dispatch = useAppDispatch();
useEffect(() => {
if (!isAuthenticated && authState && authState.isAuthenticated) {
oktaAuth.token.getUserInfo().then(info => {
//action dispatch
dispatch(authenticationSuccess({ name: info.name, email: info.email }));
});
}
}, [authState, oktaAuth]); // Update if authState changes
const renderRedirect = props => {
return isAuthenticated && <Component {...props} />;
};
return <SecureRoute {...rest} render={renderRedirect} />;
};
export default PrivateRouteComponent;
in app.js
<Security oktaAuth={oktaAuth} restoreOriginalUri={restoreOriginalUri}>
<Switch>
<Route path="/callback" component={LoginCallback} />
<PrivateRoute path="/" exact={true} component={Home} />
<PrivateRoute path="/home" exact={true} component={Home} />
</Switch>
</Security>

React.js how do i show pages depending on the status?

I want to implement a case where when users are logged in that they need to able to access the AppStack and the AuthStack. And if they not logged in, only the AuthStack will be accessible. Also when they try to access the AppStack they should get redirected. In react native I could handle this with a AuthStack and if something changed the user status he could see the one stack or the other one. But I don't know how to do it with reactjs
AuthNavigator
import React, { useState, useEffect } from 'react';
import app from './firebase';
import AuthStack from './stacks/AuthStack';
import AppStack from './stacks/AppStack';
function AuthNavigator() {
const [initializing, setInitializating] = useState(true);
const [user, setUser] = useState(true);
function onAuthStateChanged(result) {
setUser(result);
if (initializing) setInitializating(false);
if (result) {
app
.auth()
.currentUser.getIdToken(/* force Refresh */ true)
.then((idToken) => {
result.idToken = idToken;
setUser(result);
})
.catch((error) => {
console.log(error.message);
});
}
}
useEffect(() => {
const authSubscriber = app.auth().onAuthStateChanged(onAuthStateChanged);
return authSubscriber;
});
if (initializing) {
return null;
}
return user ? <AppStack user={user} /> : <AuthStack user={user} />;
}
export default AuthNavigator;
AppStack here i tried it like if there is a user then you can render the appStack else you get redirected to the authstack.
import React from 'react';
import { BrowserRouter as Router, Switch, Route } from 'react-router-dom';
import { Redirect } from 'react-router';
import Overview from '../pages/app/Overview';
import Sidebar from '../components/Sidebar/Sidebar';
function AppStack({ user }) {
return this.props.user ? (
<Router>
<Switch>
<Sidebar user={user} />
<Route path="/app-melior/overview" exact component={Overview}></Route>
</Switch>
</Router>
) : (
<Redirect path="/auth/signin"></Redirect>
);
}
export default AppStack;
AuthStack
import React from 'react';
import Navbar from '../components/Navbar/Navbar';
import { BrowserRouter as Router, Switch, Route } from 'react-router-dom';
import SignIn from '../pages/auth/SignIn';
function AuthStack({ user, app }) {
return (
<>
<Router>
<Switch>
<Route path="/auth">
<Navbar />
<Route path="/auth/signin" app={app} exact component={SignIn} />
</Route>
</Switch>
</Router>
</>
);
}
export default AuthStack;
I usually create a Private route and hanlde it like this
import React, { useState, useEffect } from 'react';
import app from './firebase';
import AuthStack from './stacks/AuthStack';
import AppStack from './stacks/AppStack';
function AuthNavigator() {
const [initializing, setInitializating] = useState(true);
const [user, setUser] = useState(true);
const PrivateRoute = ({ component, ...rest }) => {
return (
<Route
{...rest}
render={(props) =>
user ? (
<Component {...props}></Component>
) : (
<Redirect to="/auth"></Redirect>
)
}
></Route>
);
};
function onAuthStateChanged(result) {
setUser(result);
if (initializing) setInitializating(false);
if (result) {
app
.auth()
.currentUser.getIdToken(/* force Refresh */ true)
.then((idToken) => {
result.idToken = idToken;
setUser(result);
})
.catch((error) => {
console.log(error.message);
});
}
}
useEffect(() => {
const authSubscriber = app.auth().onAuthStateChanged(onAuthStateChanged);
return authSubscriber;
});
if (initializing) {
return null;
}
return
<Router>
<Switch>
<PrivateRoute path="/app>
<Sidebar user={user} />
<PrivateRoute path="/app-melior/overview" exact component={Overview}></PrivateRoute>
</PrivateRoute>
<Route path="/auth">
<Navbar />
<Route path="/auth/signin" app={app} exact component={SignIn} />
</Route>
</Switch>
</Router>;
}
export default AuthNavigator;

Categories

Resources