Current it works, but not as expected
import {Routes, Route, Navigate} from 'react-router-dom';
import appInfo from './app-info';
import routes from './app-routes';
import {SideNavOuterToolbar as SideNavBarLayout} from './layouts';
import {Footer} from './components';
export default function Content() {
return (
<SideNavBarLayout title={appInfo.title}>
<Routes>
{routes.map(({path, element}) => (
<Route
key={path}
path={path}
element={element}
/>
))}
<Route
path='*'
element={<Navigate to='/login'/>}
/>
</Routes>
<Footer>
© Bản quyền: FAMABOOK® 2018 - {new Date().getFullYear()} .
{/*<br />*/}
{/*All trademarks or registered trademarks are property of their*/}
{/*respective owners.*/}
</Footer>
</SideNavBarLayout>
);
}
it always show features inside even when not log in
I want hide menu if token in local storage did not exist, something like this
import {Routes, Route, Navigate} from 'react-router-dom';
import appInfo from './app-info';
import routes from './app-routes';
import {SideNavOuterToolbar as SideNavBarLayout} from './layouts';
import {Footer} from './components';
export default function Content() {
return (
<SideNavBarLayout title={appInfo.title}>
<Routes>
if (localStorage.getItem('token')) {
<>
{routes.map(({path, element}) => (
<Route
key={path}
path={path}
element={element}
/>
))}</>
}else{
}
<Route
path='*'
element={<Navigate to='/login'/>}
/>
</Routes>
<Footer>
2018 - {new Date().getFullYear()} .
{/*<br />*/}
{/*All trademarks or registered trademarks are property of their*/}
{/*respective owners.*/}
</Footer>
</SideNavBarLayout>
);
}
How to archive that?
CodePudding user response:
You can use &&
and render routes
conditional using conditional rendering
<Routes>
{localStorage.getItem('token') && ( // IF THERE IS A TOKEN THEN ONLY RENDER
<>
{routes.map(({ path, element }) => (
<Route key={path} path={path} element={element} />
))}
</>
)}
<Route path='*' element={<Navigate to='/login' />} />
</Routes>;
CodePudding user response:
Hey @James give this code a try-
{localStorage.getItem('token') != null || undefined ? <>
{routes.map(({path, element}) => (
<Route
key={path}
path={path}
element={element}
/>
))}</> : null }
Please try this code and if you still facing just lemme know. Thanks