Answer the question
In order to leave comments, you need to log in
How to protect routes?
Routing:
const guestRoutes = (
<Routes>
<Route path="/" element={<h1>О проекте</h1>} />
<Route path="/account" element={<h1>Войти</h1>} />
</Routes>
);
const userRoutes = (
<Routes>
<Route path="/" element={<h1>О проекте</h1>} />
<Route path="/todo-create" element={<h1>Создать</h1>} />
<Route path="/todo-update/:id" element={<h1>Редактировать</h1>} />
<Route path="/todos">
<Route index element={<h1>Задачи</h1>} />
<Route path=":id" element={<h1>Одна Задача</h1>} />
</Route>
</Routes>
);
return (
<AppContext.Provider value={{state, login, logout}}>
<Layout>
{state.isAuth ? userRoutes : guestRoutes}
</Layout>
</AppContext.Provider>
);
const userNavbar = (
<ul className="navbar__list">
<li className="navbar__item">
<NavbarLink to="/">Главная</NavbarLink>
</li>
<li className="navbar__item">
<NavbarLink to="/todos">Задачи</NavbarLink>
</li>
<li className="navbar__item">
<NavbarLink to="/todo-create">Создать</NavbarLink>
</li>
<li className="navbar__item">
<NavbarButton onClick={() => logout()}>Выйти</NavbarButton>
</li>
</ul>
);
const guestNavbar = (
<ul className="navbar__list">
<li className="navbar__item">
<NavbarLink to="/todos">Главная</NavbarLink>
</li>
<li className="navbar__item">
<NavbarLink to="/account">Войти</NavbarLink>
</li>
</ul>
);
return (
<nav className="navbar">
<div className="navbar__body">
{state.isAuth ? userNavbar : guestNavbar}
</div>
</nav>
);
Answer the question
In order to leave comments, you need to log in
It's easier to use Google and find a route recipe. Its essence lies in wrapping all routes in a function that checks either authorization or membership in a role. This is what, in fact, already exists, but is missing from the classic redirect recipe, if there is no access and a path that covers everything that is not included in the list, it is indicated by the symbol “*”.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question