Percentage
Percentage

Reputation: 93

React route v6 have NavBar for only some routes

In react-router-dom v5 I was able to do this in order for the NavBar to only show when a user was logged in and using a relevant link (not the HomePage). I can't figure out how to do this in v6. When I do something similar I get a "No route found" error for the /meds and /hist paths.

V5

<Route exact path="/" component={HomePage} />
    <Route
        path={'/(.+)'}
        render={() => (
        <div>
            <NavBar />
            <Container className="main">
                <Private exact path="/meds" component={MedicationDashboard} />
                ...

V6

<Routes>
<Route exact path='/' element={<HomePage />} />
<Route
    path={'/(.+)'}
    render={() => (
    <div>
        <NavBar />
        <div>
            <Routes>
                <Route path='/meds' element={<Medications />} />
                <Route path='/hist' element={<History />} />
            </Routes>
        </div>
    </div>
    )}
    />
</Routes>

Upvotes: 3

Views: 1796

Answers (1)

Skundlony
Skundlony

Reputation: 61

Following to react router v6 docs You can do it this way:

App.tsx

<Routes>
    <Route index element={<HomePage />} />
    <Route element={<NavbarLayout />} />
        <Route path='/meds' element={<Medications />} />
        <Route path='/hist' element={<History />} />
    </Route>
</Routes>

You will need to create component to store layout, let's call it NavbarLayout.tsx. Source code should looks like:

NavbarLayout.tsx

import { Outlet } from "react-router-dom";

export default function NavbarLayout () {
    return (
        <div>
            <NavBar />
            <div>
                <Outlet />
            </div>
        </div>
    )
}

Upvotes: 4

Related Questions