const Pages = () => {
return (
<>
<Box display="flex">
{window.location.pathname === "/profile" ? undefined : <Sidebar />}
<Box flex={3}>
<Navbar />
<Routes>
{/* Content Area */}
<Route exact path="/" element={<Dashboard />} />
<Route exact path="/calendar" element={<Calendar />} />
<Route exact path="/task" element={<div>Task</div>} />
<Route exact path="/projects" element={<div>Projects</div>} />
<Route exact path="/teamMember" element={<div>Team Member</div>} />
<Route exact path="/profile" element={<Profile />} />
{/* Error Path */}
<Route path="*" element={<div>404</div>} />
</Routes>
</Box>
</Box>
</>
);
};enter code here
Hello, where do I put my error path because when it renders, it renders on my content area?
It is because you continually render a layout(Box, Sidebar, Navbar). There are a few options in order to achieve your request you have to either:
create a Layout component that will render Box, Sidebar, and Navbar inside and use that Layout inside your pages, for example:
const Dashboard = () => {
// ...
return (
<Layout>
Dashboard content
</Layout>
)
}
or use the benefit of the new latest react-router package:
import { Outlet } from 'react-router-dom'
const Layout = () => {
return (
<Box display="flex">
{window.location.pathname === "/profile" ? undefined : <Sidebar />}
<Box flex={3}>
<Navbar />
<Outlet /> {/* Roughly speaking this is `children`. Refer to the documentation */}
</Box>
)
}
<Routes>
<Route element={<Layout />} path="/">
<Route index element={<Dashboard />} />
<Route path="/calendar" element={<Calendar />} />
<Route path="/task" element={<div>Task</div>} />
<Route path="/projects" element={<div>Projects</div>} />
<Route path="/teamMember" element={<div>Team Member</div>} />
<Route path="/profile" element={<Profile />} />
</Route>
<Route path="*" element={<div>404</div>} />
</Routes>
Related
[[Link]enter image description here(https://i.stack.imgur.com/CopPx.png)
[enter image description here](https://i.stack.imgur.com/VPoTE.png)
I tried to make a function to set product with setState and in the same time to set the route to product.strMeal(name). The problem is that when i click on the Link tag my route does not update.
<div className="category-container">
{
category.map(meal => {
return (
isLoading ? <Loader /> : (
<Link onClick={() => getClickedProductCompleteInfo(meal.strMeal)} to={`/${product.strMeal}`} className="meal-card" key={meal.idMeal}>
<h3>{meal.strMeal}</h3>
<img className='meal-thumbnail' src={meal.strMealThumb} style={{ width: 200, height: 200 }} alt="meal" />
</Link>
)
)
})
}
</div>
const getClickedProductCompleteInfo = async (meal: string) => {
const productCompleteInfo = await getDataFromApi(`https://www.themealdb.com/api/json/v1/1/search.php?s=${meal}`);
setProduct(productCompleteInfo.meals[0]);
}
<Routes>
<Route path="/" >
<Route index element={<Home isLoading={isLoading} categories={categories} setCurrentCategory={setCurrentCategory} />} />
<Route path={`categories/${currentCategory}`} element={<Category product={product} setProduct={setProduct} currentCategory={currentCategory} getDataFromApi={getDataFromApi} />} />
<Route path={`${product.strMeal}`} element={<Product product={product}/>}/>
<Route path='about' element={<About />} />
<Route path='contact' element={<Contact />} />
<Route path='*' element={<Navigate to="/"></Navigate>} />
</Route>
</Routes>
I'm getting this error when I wrap some of my routes in a Context Provider tag. I basically need to send the logged user context to each of these routes for them to use or modify. The value sent in the provider is this:
const [loggedUser, setLoggedUser] = useState(null)
const value = useMemo(() => {{ loggedUser, setLoggedUser }}, [loggedUser, setLoggedUser])
And here is the code:
return (
<>
<Routes>
<Route path="/" element={ <MainPage /> } />
<UserContext.Provider value={value}>
<Route path="/login" element={<LoginMenu/>} />
<Route path="/register" element={<RegisterMenu/>} />
<Route path="/dashboard" element={<Dashboard tasks={tasks} />} />
</UserContext.Provider>
</Routes>
</>
)
Only Route component can be a child of a Route component. Abstract the UserContext.Provider component into a layout route.
Example:
import { Routes, Route, Outlet } from 'react-router-dom';
const UserContextProvider = () => (
<UserContext.Provider value={value}>
<Outlet />
</UserContext.Provider>
);
...
<Routes>
<Route path="/" element={<MainPage />} />
<Route element={<UserContextProvider />}>
<Route path="/login" element={<LoginMenu />} />
<Route path="/register" element={<RegisterMenu />} />
<Route path="/dashboard" element={<Dashboard tasks={tasks} />} />
</Route>
</Routes>
Or wrap the entire Routes in the UserContext.Provider component.
Example:
return (
<UserContext.Provider value={value}>
<Routes>
<Route path="/" element={ <MainPage /> } />
<Route path="/login" element={<LoginMenu />} />
<Route path="/register" element={<RegisterMenu />} />
<Route path="/dashboard" element={<Dashboard tasks={tasks} />} />
</Routes>
</UserContext.Provider>
);
How to render Overlay component just for a one time instead of rendering it in each Route.
Here is code of my App.js
function App() {
return (
<div className="App">
<Navbar />
<div className='container'>
<Sidebar />
<Routes>
<Route path='/' element={<Overlay pathName={'Главная'} />} />
<Route path='/orders' element={<Overlay pathName={'Заказы'} />} />
<Route path='/products' element={<Overlay pathName={'Товары'} />} />
<Route path='/reviews' element={<Overlay pathName={'Отзывы'} />} />
<Route path='/checkout' element={<Overlay pathName={'Оформить заказ'} />} />
</Routes>
</div>
</div>
);
}
<Routes>
{
[
{url:'/',pathname:'abc'},
{url:'/orders',pathname:'def'},
{url:'/products',pathname:'ghi'},
{url:'/reviews',pathname:'jkl'},
{url:'/checkout',pathname:'mno'},
].map(elem=><Route key={elem.url} path={elem.url} element={<Overlay pathname={elem.pathname}/>} />)
}
<Routes />
I'm creating an aplication with any routes and sub routes. This aplication has a SideBar with link to routes(pages) and this routes(pages) has links to subroutes(subpages). I want to set active class when the link match(non exactly), example:
links:
/users
/teams
/settings
(/teams/name-of-team/squads) => /teams OK!
(/users/teams/234) => /users OK!
Now, i'm using react router dom v6v example(https://stackblitz.com/github/remix-run/react-router/tree/main/examples/custom-link?file=src%2FApp.tsx) but this return true only when match exactly!
The routes:
<BrowserRouter>
<Routes>
<Route path="status" element={<Status />} />
<Route path="login" element={<Login />} />
<Route path="forgot-password" element={<ForgotPassword />} />
<Route path="reset-password/:token" element={<ResetPassword />} />
<Route path="/" element={<LoggedArea />}>
{/* Inicio */}
<Route index element={<Personal />} />
{/* Dashboards */}
<Route path="dashboards">
<Route index element={<Dashboards />} />
</Route>
{/* Vagas */}
<Route path="jobs">
<Route index element={<Jobs />} />
<Route path=":name" element={<Jobs />} />
</Route>
{/* Documentos */}
<Route path="documents">
<Route index element={<Files />} />
<Route path="*" element={<Files />} />
</Route>
{/* Usuários */}
<Route path="users">
<Route index element={<Users />} />
<Route path="create" element={<CreateUser />} />
<Route path=":name" element={<User />} />
</Route>
{/* Times */}
<Route path="teams">
<Route index element={<Teams />} />
<Route path=":name" element={<Team />}>
<Route index element={<Heading3>Resumo</Heading3>} />
<Route path="overview" element={<Heading3>Resumo</Heading3>} />
<Route path="goals" element={<TeamGoals />} />
<Route path="squads" element={<TeamSquads />} />
<Route path="settings" element={<TeamSettings />} />
</Route>
</Route>
{/* Componentes */}
<Route path="ui">
<Route index element={<Ui />} />
</Route>
{/* Configurações */}
<Route path="settings" element={<Settings />}>
<Route index element={<ProfileSettings />} />
<Route path="profile" element={<ProfileSettings />} />
<Route path="security" element={<SecuritySettings />} />
</Route>
</Route>
<Route path="*" element={<NotFound />} />
</Routes>
</BrowserRouter>
My custom link component:
interface SideMenuItemProps {
icon : React.ReactNode;
label: string;
url: string;
tooltip?: boolean;
}
export function SideMenuItem(props: SideMenuItemProps) {
const resolved = useResolvedPath(props.url)
const match = useMatch({
path: resolved.pathname,
end: true
})
return(
<li className={styles.item}>
<Tooltip disabled={!props.tooltip} label={props.label} >
<Link to={props.url} className={`${styles.link} ${match ? styles.active : ''} `}>
{props.icon}
</Link>
</Tooltip>
</li>
)
}
Route.js
const Layout = () => {
const SecuredRoute = ({ ...props }) => (
console.log(props.path),
<Route path={props.path} render={(data) => (
console.log(data),
localStorage.getItem('accessToken')
? <props.render {...data} />
: <Redirect to='/login' />
)} />
)
return (
<>
<BrowserRouter>
<Navbar /> // It needs to be hidden if user is not logged in
<div className='layout'>
<Switch>
<Route exact path='/home' component={Home} />
<Route exact path='/login' component={Login} />
<SecuredRoute exact path='/about' component={About} />
<Route exact path='/contact' component={Contact} />
<Route exact path='/add' component={AddBlog} />
<Route exact path='/edit/:id' component={UpdateBlog} />
<Route exact path='/blog/:id' component={Blogdetail} />
<Route component={Home} />
</Switch>
</div>
<Footer />
</BrowserRouter>
</>
)
}
export default Layout
I want if the user is not logged in then navbar must be hidden. It means when route = '/login' navbar needs to be hidden. u have tried out many things but nothing works. I am new to React. Any help will be appreciated?
You can create a boolean variable and short-circuit it.
render() {
const visible = true;
const notVisible = false;
return (
<div>
{visible && <p>I am visible</p>}
{notVisible && <p>I am not visible</p>}
</div>
);
}
Try this in the Navbar component my friend:
const [loggedIn, setLoggedIn] = useState(false);
const Layout = () => {
const SecuredRoute = ({ ...props }) => (
console.log(props.path),
<Route path={props.path} render={(data) => (
console.log(data),
localStorage.getItem('accessToken')
? <props.render {...data} />
: <Redirect to='/login' />
)} />
)
return (
<>
<BrowserRouter>
<Navbar loggedIn={loggedIn} /> // It needs to be hidden if user is not logged in
<div className='layout'>
<Switch>
<Route exact path='/home' component={Home} />
<Route exact path='/login' component={() => <Login setLoggedIn={setLoggedIn} />} />
<SecuredRoute exact path='/about' component={About} />
<Route exact path='/contact' component={Contact} />
<Route exact path='/add' component={AddBlog} />
<Route exact path='/edit/:id' component={UpdateBlog} />
<Route exact path='/blog/:id' component={Blogdetail} />
<Route component={Home} />
</Switch>
</div>
<Footer />
</BrowserRouter>
</>
)
}
export default Layout
I gave a setState to login component. You give a true boolean when the user logs in, loggedIn(true) and the parent state changes.
And in the Navbar component:
return(
loggedIn
?
//The Body of NavBar
:
""
}
)