const Navbar = () => {
return (
<div>
{location === '/' ? (
<AuthNav />
) : location === '/home' && isAuthenticated ? (
<MainNav />
) : <AuthNav />
}
</div>
);
};
How do I render two separate navbars on different application routes, in this case, I want to render the AuthNav in the login and signup path and I want to render MainNav on the home path.
Issues
I think you've a few things working against you:
The Navbar component is unconditionally rendered and using window.location.pathname to compute which actual navigation component to render. This means the view to be rendered is only computed when the Navbar component rerenders.
The Navbar component is rendered outside the Routes, so it's not rerendered when a route changes.
Solution
Instead of unconditionally rendering Navbar and trying to compute which nav component to render based on any current URL pathname, split them out into discrete layout routes that render the appropriate nav component.
Example:
Navbar.jsx
export const AuthNav = ({ auth }) => {
....
};
export const MainNav = () => {
....
};
App.jsx
import { Routes, Route, Navigate, Outlet } from 'react-router-dom';
import { useState } from "react";
// components
import { AuthNav, MainNav } from './components/Navbar';
// pages
...
...
const AuthLayout = ({ auth }) => (
<>
<AuthNav auth={auth} />
<Outlet />
</>
);
const MainLayout = () => (
<>
<MainNav />
<Outlet />
</>
);
const PrivateRoute = ({ auth }) => {
return auth.isAuthenticated
? <Outlet />
: <Navigate to="/" replace />;
};
const App = () => {
const [isAuthenticated, setIsAuthenticated] = useState(false);
return (
<div className='parent'>
<Routes>
<Route element={<AuthLayout auth={{ isAuthenticated, setIsAuthenticated }} />}>
<Route path='/' element={<SignIn />} />
<Route path='/signup' element={<SignUp />} />
</Route>
<Route element={<MainLayout />}>
<Route element={<PrivateRoute auth={{ isAuthenticated }} />}>
<Route path='/Home' element={<Home />} />
<Route path='/music' element={<Music />} />
<Route path='/genre/' element={<Pop />} />
<Route path='/Hiphop' element={<HipHop />} />
<Route path='/Rock' element={<Rock />} />
<Route path='/EDM' element={<EDM />} />
<Route path='/Jazz' element={<Jazz />} />
<Route path='/RandB' element={<RandB />} />
<Route path='/store' element={<Store />} />
<Route path='/News' element={<News />} />
<Route path='/Contact' element={<Contact />} />
<Route path='/album/:id' element={<Album />} />
<Route path ="/album/:id/nested/" element={<Albums2 />} />
</Route>
</Route>
</Routes>
</div>
);
};
Related
I have written AuthContext.js in a seprate file like bellow
export const AuthContext = createContext({
isLoggedIn: false,
login: () => {},
logout: () => {},
});
const AuthContextProvider = (props) => {
const [isLoggedIn, setIsLoggedIn] = useState(false);
const loginHandler = useCallback(() => {
setIsLoggedIn(true);
}, []);
const logoutHandler = useCallback(() => {
setIsLoggedIn(false);
}, []);
const initialValue = {
isLoggedIn: isLoggedIn,
login: loginHandler,
logout: logoutHandler,
};
return (
<AuthContext.Provider value={initialValue}>
{props.children}
</AuthContext.Provider>;
);
};
export default AuthContextProvider;
Then I import them manually in App.js
I recognized that when do I login, App.js never re-render even the value of isLoggedIn changed.
Result in routes variable never gotten new values, components will not change as well.
The App.js file
const App = () => {
const authCtx = useContext(AuthContext);
const { isLoggedIn } = authCtx;
let routes;
if (isLoggedIn) {
routes = (
<Switch>
<Route path="/" exact>
<Users />
</Route>
<Route path="/places/new" exact>
<NewPlace />
</Route>
<Route path="/:userId/places" exact>
<UserPlaces />
</Route>
<Route path="/places/:placeId">
<UpdatePlace />
</Route>
<Redirect to="/" />
</Switch>
);
}
else {
routes = (
<Switch>
<Route path="/" exact>
<Users />
</Route>
<Route path="/:userId/places" exact>
<UserPlaces />
</Route>
<Route path="/signin" exact>
<SignIn />
</Route>
<Route path="/signup" exact>
<Signup />
</Route>
<Redirect to="/signin" />
</Switch>
);
}
return (
<AuthContextProvider>
<BrowserRouter>
<MainNavigation />
<main>{routes}</main>
</BrowserRouter>
</AuthContextProvider>
);
};
export default App;
What is my mistake in this case.
If App is the component rendering the AuthContextProvider component then it can't access the Context value it provides. The AuthContextProvider must be rendered higher in the ReactTree in order for App to be able to access the Context value. Current App is receiving the default value that was passed to React.createContext.
export const AuthContext = createContext({
isLoggedIn: false,
login: () => {},
logout: () => {},
});
The default value is used when there is not any Context provider higher in the ReactTree.
Move AuthContextProvider to be higher in the ReactTree, i.e. wrap App.
App
const App = () => {
const { isLoggedIn } = useContext(AuthContext);
let routes;
if (isLoggedIn) {
routes = (
<Switch>
<Route path="/" exact>
<Users />
</Route>
<Route path="/places/new" exact>
<NewPlace />
</Route>
<Route path="/:userId/places" exact>
<UserPlaces />
</Route>
<Route path="/places/:placeId">
<UpdatePlace />
</Route>
<Redirect to="/" />
</Switch>
);
}
else {
routes = (
<Switch>
<Route path="/" exact>
<Users />
</Route>
<Route path="/:userId/places" exact>
<UserPlaces />
</Route>
<Route path="/signin" exact>
<SignIn />
</Route>
<Route path="/signup" exact>
<Signup />
</Route>
<Redirect to="/signin" />
</Switch>
);
}
return (
<>
<MainNavigation />
<main>{routes}</main>
</>
);
};
export default App;
<AuthContextProvider>
<BrowserRouter>
<App />
</BrowserRouter>
</AuthContextProvider>
Can anyone tell me what's wrong in this code ??
I am protecting the route but the error is comming .
I have creted a ProtectionRoute component which calls AUTH_FUNC(Checks whether user is locked in or not) from the TwitterState.js and if the user is logged in then the ProtectionRoute returns the Component and else redirect to the login page !
App.js
import {BrowserRouter as Router , Routes , Route , useNavigate} from "react-router-dom"
import Home from "./pages/Home"
import Auth from "./pages/Auth"
import Profile from "./pages/Profile"
import Bookmark from "./pages/Bookmark"
import NotFound from "./pages/NotFound"
import Explore from "./pages/Explore"
import TrendingTags from "./pages/TrendingTags"
import Discover from "./pages/Discover"
import { ToastContainer, toast } from 'react-toastify';
import 'react-toastify/dist/ReactToastify.css';
import Register from "./pages/Register"
import EditProfile from "./pages/EditProfile"
import ProtectedRoute from "./components/ProtectedRoute"
function App() {
return (
<Router>
<ToastContainer />
<Routes>
<Route path="/" element={<ProtectedRoute><Home/></ProtectedRoute>}/>
<Route path="/auth" element={<ProtectedRoute><Auth/></ProtectedRoute>}/>
<Route path="/profile" element={<ProtectedRoute><Profile/></ProtectedRoute>} />
<Route path="/message" element={<ProtectedRoute><NotFound/></ProtectedRoute>} />
<Route path="/notifications" element={<ProtectedRoute><NotFound/></ProtectedRoute>} />
<Route path="/bookmark" element={<ProtectedRoute><Bookmark/></ProtectedRoute>} />
<Route path="/explore" element={<ProtectedRoute><Explore/></ProtectedRoute>} />
<Route path="/explore/trending/:tagName" element={<ProtectedRoute><TrendingTags/></ProtectedRoute>} />
<Route path="/discover" element={<ProtectedRoute><Discover/></ProtectedRoute>} />
<Route path="/register" element={<ProtectedRoute><Register /></ProtectedRoute>} />
<Route path="/profile/edit" element={<ProtectedRoute><EditProfile /></ProtectedRoute>} />
</Routes>
</Router>
);
}
export default App;
ProtectedRoute.js
import React , {useContext} from "react";
import { Route, Navigate } from "react-router-dom";
import TwitterContext from "../context/TwitterContext";
export default function ProtectedRoute ({children}) {
const {AUTH_FUNC} = useContext(TwitterContext)
const loggedin = AUTH_FUNC()
if(!loggedin){
return <Navigate to="/auth"/>
}
return children
};
Twitter.jsx
import TwitterContext from "./TwitterContext";
const TwitterState = (props) => {
const AUTH_FUNC = () =>{
const res = JSON.parse(localStorage.getItem("UserData"))
if(res !== null){
return true
}
return false
}
return <TwitterContext.Provider value={{AUTH_FUNC}}>
{props.children}
</TwitterContext.Provider>
}
export default TwitterState
Error :
Issue
You are protecting the "/auth" route as well, which when a user is not authenticated yet will create a navigation loop from "/auth" to "/auth", repeat ad nauseam.
function App() {
return (
<Router>
<ToastContainer />
<Routes>
...
<Route path="/auth" element={<ProtectedRoute><Auth/></ProtectedRoute>}/>
...
</Routes>
</Router>
);
}
export default function ProtectedRoute ({ children }) {
const { AUTH_FUNC } = useContext(TwitterContext);
const loggedin = AUTH_FUNC();
if (!loggedin) {
return <Navigate to="/auth"/>;
}
return children;
};
Solution
You don't want to protect the authentication route the same way as the routes that require authentication. Remove ProtectedRoute from the "/auth" route.
Refactor the ProtectedRoute to render an Outlet also so you can make the code more DRY. This allows the ProtectedRoute component to wrap entire sets of routes that need to be protected.
import { Navigate, Outlet } from 'react-router-dom';
export default function ProtectedRoute () {
const { AUTH_FUNC } = useContext(TwitterContext);
const loggedin = AUTH_FUNC();
if (loggedin === undefined) {
return null; // or loading indicator/spinner/etc
}
return loggedin
? <Outlet />
: <Navigate to="/auth" replace />;
};
function App() {
return (
<Router>
<ToastContainer />
<Routes>
{/* Unprotected routes */}
<Route path="/auth" element={<Auth />} />
<Route path="/register" element={<Register />} />
{/* Protected routes */}
<Route element={<ProtectedRoute />}>
<Route path="/" element={<Home />} />
<Route path="/profile" element={<Profile />} />
<Route path="/message" element={<NotFound />} />
<Route path="/notifications" element={<NotFound />} />
<Route path="/bookmark" element={<Bookmark />} />
<Route path="/explore" element={<Explore />} />
<Route path="/explore/trending/:tagName" element={<TrendingTags />} />
<Route path="/discover" element={<Discover />} />
<Route path="/profile/edit" element={<EditProfile />} />
</Route>
</Routes>
</Router>
);
}
It's also a common pattern to protect the "anonymous" routes from authenticated users. For this create another protected route component that does the inverse of the ProtectedRoute component.
import { Navigate, Outlet } from 'react-router-dom';
export default function AnonymousRoute () {
const { AUTH_FUNC } = useContext(TwitterContext);
const loggedin = AUTH_FUNC();
if (loggedin === undefined) {
return null; // or loading indicator/spinner/etc
}
return loggedin
? <Navigate to="/" replace />
: <Outlet />;
};
function App() {
return (
<Router>
<ToastContainer />
<Routes>
{/* Anonymous routes */}
<Route element={<AnonymousRoute />}>
<Route path="/auth" element={<Auth />} />
<Route path="/register" element={<Register />} />
</Route>
{/* Protected routes */}
<Route element={<ProtectedRoute />}>
<Route path="/" element={<Home />} />
<Route path="/profile" element={<Profile />} />
<Route path="/message" element={<NotFound />} />
<Route path="/notifications" element={<NotFound />} />
<Route path="/bookmark" element={<Bookmark />} />
<Route path="/explore" element={<Explore />} />
<Route path="/explore/trending/:tagName" element={<TrendingTags />} />
<Route path="/discover" element={<Discover />} />
<Route path="/profile/edit" element={<EditProfile />} />
</Route>
</Routes>
</Router>
);
}
The Auth is in protected route and causes the navigation loop.
<Route path="/auth" element={<ProtectedRoute><Auth/></ProtectedRoute>}/>
export default function ProtectedRoute ({children}) {
const {AUTH_FUNC} = useContext(TwitterContext)
const loggedin = AUTH_FUNC()
if(!loggedin){
return <Navigate to="/auth"/>
}
return children
};
/auth route probably shouldn't be a protected route, in order to function normally.
This question already has answers here:
How to create a protected route with react-router-dom?
(5 answers)
Closed 4 months ago.
Help
I'm using a protected route in my React app. But it is not working. All the other Elements are working but when I got to "/account" the whole screen is white. This is my code. It will be really helpful for me if you give that answer. Thank You :)
Protected Route code:
import React, { Fragment } from 'react';
import { useSelector } from 'react-redux';
import { Route, Routes, redirect } from 'react-router-dom';
const ProtectedRoute = ({ element: Element, ...rest }) => {
const { loading, isAuthenticated, user } = useSelector(state => state.user);
return (
<Fragment>
{!loading &&
(<Routes>
<Route
{...rest}
render={(props) => {
if(!isAuthenticated) {
return redirect("/login")
}
return <Element {...props} />
}}
/>
</Routes>
)}
</Fragment>
)
}
export default ProtectedRoute;
I am using ProtectedRoute.js in App.js. Here is the code.
App.js Code:
import React from 'react';
import {BrowserRouter as Router,Route,Routes} from "react-router-dom";
import './App.css';
import Header from "./component/layout/Header/Header.js";
import webFont from "webfontloader";
import Footer from './component/layout/Footer/Footer';
import Home from "./component/Home/Home.js";
import ProductDetails from "./component/Product/ProductDetails.js";
import Products from "./component/Product/Products.js";
import Search from "./component/Product/Search.js";
import LoginSignUp from './component/User/LoginSignUp';
import store from "./store";
import { loadUser } from './action/userAction';
import UserOption from "./component/layout/Header/UserOption.js";
import { useSelector } from 'react-redux';
import Profile from "./component/User/Profile.js"
import ProtectedRoute from './component/Route/ProtectedRoute';
function App() {
const {isAuthenticated, user} = useSelector(state => state.user)
React.useEffect(() => {
webFont.load({
google:{
families:["Roboto","Droid Sans","Chilanka"]
},
});
store.dispatch(loadUser())
}, [])
return (
<Router>
<Header />
{isAuthenticated && <UserOption user={user} />}
<Routes>
<Route path="/" element={<Home />} />
<Route path="/product/:id" element={<ProductDetails />} />
<Route path="/products" element={<Products />} />
<Route path="/products/:keyword" element={<Products />} />
<Route path="/search" element={<Search />} />
<Route path="/account" element={ <ProtectedRoute> <Profile /> </ProtectedRoute> } />
<Route path="/login" element={<LoginSignUp />} />
</Routes>
<Footer />
</Router>
);
}
export default App;
In your App.js you can declare the protected route like this
<Route path="/account" element={ <ProtectedRoute /> } >
<Route path="/account" element={ <Profile /> } >
</Route>
You can use Outlet of react-router v6 for passing the Component
const ProtectedRoute = ({ element: Element, ...rest }) => {
const { loading, isAuthenticated, user } = useSelector(state => state.user);
if (loading) {
return <h2>Loading...</h2>
}
return isAuthenticated ? <Outlet /> : <Navigate to="/login" />;
}
# Sayedul Karim.
I have a better and more concise way for this, An example of the code is below.
<Routes>
<Route element={<App />}>
{isAuthenticated ? (
<>
<Route path="/*" element={<PrivateRoutes />} />
<Route
index
element={<Navigate to="/account" />}
/>
</>
) : (
<>
<Route path="auth/*" element={<AuthPage />} />
<Route path="*" element={<Navigate to="/auth" />} />
</>
)}
</Route>
</Routes>
In this way, you don't have to make any private component instead just make a component for private routes where the routes are defined.
The PrivateRoutes component will be like this
<Routes>
<Route>
{/* Redirect to account page after successful login */}
{/* Pages */}
<Route path="auth/*" element={<Navigate to="/account" />} />
<Route path="account" element={<Account />} />
</Routes>
If any query further, feel free to ask....
I'm not sure, but you haven't pass any "element" prop to your ProtectedRoute component. You pass Profile component as children, so try render children instead of element in ProtectedRoute if you want your code to work like this.
I believe that you might want not to nest those routes, so also you might want to try use ProtectedRoute as Route in your router, I'm talking about something like this
<Routes>
...
<ProtectedRoute path="/account" element={<Profile />} />
...
</Routes>
UPDATE
It might show you this error because your Route is conditionally rendered, so try to handle loading state in some other way, maybe something like this
return (
<Route
{...rest}
render={(props) => {
if(!isAuthenticated) {
return redirect("/login")
}
if(loading) {
return <LoadingComponent />
}
return <Element {...props} />
}}
/>
)
I don't understand why this code is not working. "isAuthenticated" is a boolean from the moralis API. If it is true it should render outlet and if it's false should render the navigate option.
const ProtectedRoutes = () => {
const { isAuthenticated } = useMoralis();
return isAuthenticated ? <Outlet /> : <Navigate to="/" />;
};
return (
<Routes>
<Route path={ROUTER_PATHS.SIGNUP} element={<Signup />} />
<Route element={<ProtectedRoutes />}>
<Route path={ROUTER_PATHS.EMPLOYER} element={<MarketPlaceEmployer />} />
<Route path={ROUTER_PATHS.EMPLOYEE} element={<MarketPlaceEmployee />} />
</Route>
</Routes>
);
Using <Outlet /> component will make ProtectedRoutes component as Layout component to make ProtectedRoutes work as wrapping component as well you should optionally render children, change ProtectedRoutes component as,
const ProtectedRoutes = ({ children }) => {
const { isAuthenticated } = useMoralis();
if (!isAuthenticated) {
return <Navigate to="/" />;
}
return children ? children : <Outlet />;
};
Also, add exact before path,
return (
<Routes>
<Route path={ROUTER_PATHS.SIGNUP} element={<Signup />} />
<Route element={<ProtectedRoutes />}>
<Route exact path={ROUTER_PATHS.EMPLOYER} element={<MarketPlaceEmployer />} />
<Route exact path={ROUTER_PATHS.EMPLOYEE} element={<MarketPlaceEmployee />} />
</Route>
</Routes>
I am new to React & React-Router#v6.
I was upgrading to react-router v6 from v5.3, and updated my local routes to v6 architecture.
v5 route file
import { lazy } from 'react';
import { Route, Switch } from 'react-router-dom';
const SchoolRoutes = () => {
const login = lazy(() => import('./login/login'));
// Component from Other Library as home page and acts as initial route
const home = lazy(() => import('#portal-school/home').then(({ Home }) => ({ default: Home })));
// Routes from Other libs
const studentRoutes = lazy(() => import('#portal-school/school').then(({ Students }) => ({ default: Students, })));
const activitiesRoutes = lazy(() => import('#portal-school/school').then(({ Activities }) => ({ default: Activities, })));
const reportRoutes = lazy(() => import('#portal-school/reports').then(({ ReportRoutes }) => ({ default: ReportRoutes, })));
return (
<Switch>
<Route exact path="/" component={home} />
<Route exact path="/login" component={login} />
<Route path="/students" component={studentRoutes} />
<Route path="/activities" component={activitiesRoutes} />
<Route path="/school-reports" component={reportRoutes} />
</Switch>
);
};
export default SchoolRoutes;
v6 route file
import React,{ lazy } from 'react';
import { Route, Routes } from 'react-router-dom';
const SchoolRoutes = () => {
const Login = lazy(() => import('./login/login'));
// Below is the home component that to be loaded.
const Home = lazy(() => import('#portal-school/home').then(({ UserLogs }) => ({ default: UserLogs })));
// Below are the routes from other libs to be loaded.
const StudentRoutes = lazy(() => import('#portal-school/school').then(({ Students }) => ({ default: Students, })));
const ActivitiesRoutes = lazy(() => import('#portal-school/school').then(({ Activities }) => ({ default: Activities, })));
const ReportRoutes = lazy(() => import('#portal-school/reports').then(({ ReportRoutes }) => ({ default: ReportRoutes, })));
return (
<Routes>
<Route path="/" element={<Home />} />
<Route path="/login" element={<Login />} />
<Route path="/students/*" element={<StudentRoutes />} />
<Route path="/activities/*" element={<ActivitiesRoutes />} />
<Route path="/school-reports/*" element={<ReportRoutes />} />
</Routes>
);
};
export default SchoolRoutes;
Main App component
function App(){
return (
<BrowserRouter>
<AppBar className="app-header">
<div className="school-logo"></div>
</AppBar>
<SideMenu/>
//Injecting Routes Below
<main className="main-blk">
<Suspense fallback={<CircularProgress />}> // Circular Progress is loading
// School Routes file injected below.
<SchoolRoutes/>
</Suspense>
</main>
</BrowserRouter>
)
}
So While trying to access the routes, the home screen is not loading, only Suspense fallback Message Renders, and when I try to access other Route Links, there is the same issue.
Components are not loading through the routes. Can anyone share a solution ?.
Update: I solved by moving the Suspense from App to SchoolRoutes.
Old SchoolRoutes File
<Routes>
<Route path="/" element={<Home />} />
<Route path="/login" element={<Login />} />
<Route path="/students/*" element={<StudentRoutes />} />
<Route path="/activities/*" element={<ActivitiesRoutes />} />
<Route path="/school-reports/*" element={<ReportRoutes />} />
</Routes>
Updated SchoolRoutes File
<Suspense fallback={<CircularProgress />}>
<Routes>
<Route path="/" element={<Home />} />
<Route path="/login" element={<Login />} />
<Route path="/students/*" element={<StudentRoutes />} />
<Route path="/activities/*" element={<ActivitiesRoutes />} />
<Route path="/school-reports/*" element={<ReportRoutes />} />
</Routes>
<Suspense/>