I want to put a div inside <Routes>
and also Render a <Topbar />
and <Sidebar />
component inside <Routes>
without <Route>
tag for them.
My code is as follows:-
const App = () => {
return (
<Router>
<Routes>
<Route path="login" element={<Login />} />
<Topbar />
<div className="container">
<Sidebar />
<Route path="/" element={<Home />} />
<Route path="users" element={<UserList />} />
</div>
</Routes>
</Router>
);
};
I want to implement <Topbar />
and <Sidebar />
for all the routes.
But for an exception of login Page (Topbar
and Sidebar
should not be shown on the login page).
That's why I had put login Route at the top of Topbar
and Sidebar
.
The console is showing error as:
Uncaught Error: [Topbar] is not a
<Route>
component. All component children of<Routes>
must be a<Route>
or<React.Fragment>
How to implement this functionality?
CodePudding user response:
In react-router-dom
v6 only Route
and React.Fragment
components are valid children for the Routes
component.
Use layout components to render the Topbar
and Sidebar
components along with an Outlet
for nested routes for the routes you want to render these components.
Example:
import { Routes, Route, Outlet } from 'react-router-dom';
const Layout = () => (
<>
<Topbar />
<div className="container">
<Sidebar />
<Outlet />
</div>
</>
);
const App = () => {
return (
<Router>
<Routes>
<Route path="/login" element={<Login />} />
<Route element={<Layout />}>
<Route path="/" element={<Home />} />
<Route path="users" element={<UserList />} />
</Route>
</Routes>
</Router>
);
};
CodePudding user response:
Change your routes like below,
you need to check whether user is logged in or not, if user logged in use Tobbar, Sidebar etc, otherwise just return login route
const App = () => {
const [isLogin, setIsLogin] = useState(false)
return (
<Router>
<Routes>
{ isLogin ? <Topbar />
<div className="container">
<Sidebar />
<Route path="/" element={<Home />} />
<Route path="users" element={<UserList />} />
</div> : <Route path="login" element={<Login />} />
</Routes>
</Router>
);
};