I am new to React and I am following this project. But I am stuck on converting the nested routed in version6 of react-router-dom.
In V5 it is as follows:
App.js
return (
<div>
<Header />
<Switch>
<Route exact path='/' component={HomePage} />
<Route path='/shop' component={ShopPage} />
<Route exact path='/checkout' component={CheckoutPage} />
<Route
exact
path='/signin'
render={() =>
this.props.currentUser ? (
<Redirect to='/' />
) : (
<SignInAndSignUpPage />
)
}
/>
</Switch>
</div>
);
ShopPage
const ShopPage = ({ match }) => (
<div className='shop-page'>
<Route exact path={`${match.path}`} component={CollectionsOverview} />
<Route path={`${match.path}/:collectionId`} component={CollectionPage} />
</div>
);
I want to convert it in V6 and I had tried as follows:
My App.js
return (
<div >
<Header />
<Routes>
<Route path='/' element={<HomePage />} />
<Route path='/shop' element={<ShopPage />} />
<Route path='/checkout' element={<CheckoutPage />} />
<Route path='/signin' element={<>
{this.props.currentUser ?
<Navigate to="/" />
:
<SignInAndSignUpPage />
}
</>
}
/>
<Route path='/signin' element={this.props.user ? <Navigate to="/" /> : <SignInAndSignUpPage />} />
</Routes>
</div>
);
My Shopage
const ShopPage = () => {
let { pathname } = useLocation();
console.log(pathname);
return (
<div className='shop-page'>
<Routes>
<Route path={`${pathname}`} element={<CollectionsOverview />} />
<Route path={`${pathname}/:collectionId`} element={<CollectionItems />} />
</Routes>
</div>
)
};
In pathname console log I am getting /shop but the items are not showing.
How can acheive nested routing in v6?
It looks like CollectionsOverview is what is rendered exactly on "/shop". Nested routes operate a little different in v6 than they did in v5. You don't need to get the current path/url to build nested routes/links, you can just use relative routes.
Example:
const ShopPage = () => {
return (
<div className='shop-page'>
<Routes>
<Route path="/" element={<CollectionsOverview />} />
<Route path=":collectionId" element={<CollectionItems />} />
</Routes>
</div>
);
};
Optionally, you can can convert ShopPage into a layout route.
Example:
import { Outlet } from 'react-router-dom';
const ShopPage = () => (
<div className='shop-page'>
<Outlet />
</div>
);
App
return (
<div >
<Header />
<Routes>
<Route path='/' element={<HomePage />} />
<Route path='/shop' element={<ShopPage />}>
<Route index element={<CollectionsOverview />} />
<Route path=":collectionId" element={<CollectionItems />} />
</Route>
<Route path='/checkout' element={<CheckoutPage />} />
<Route
path='/signin'
element={this.props.currentUser
? <Navigate to="/" />
: <SignInAndSignUpPage />
}
/>
<Route
path='/signin'
element={this.props.user
? <Navigate to="/" />
: <SignInAndSignUpPage />
}
/>
</Routes>
</div>
);