You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Ran into an issue when trying to nest Switches for these routes.
Going to a route that is contained inside the inner Switch it will redirect to /products if I was using Redirect. To try to work around that I replaced Redirect with a fallback route, but this solution only works if isLoggedIn is false so to fix that I also added a fallback route inside the inner Switch.
But this doesn't seem right. Is there a better way to implement this? This is my first time submitting an issue please excuse my lack of formatting.
<Switch>
{/* Routes placed here are available to all visitors */}
<Route exact path="/login" component={Login} />
<Route exact path="/register" component={RegisterForm} />
<Route exact path="/product/:id" component={ProductDetails} />
<Route exact path="/products" component={Products} />
<Route exact path="/cart" component={Cart} />
{/* Routes placed here are only available after logging in */}
{isLoggedIn && (
<Switch>
<Route exact path="/user" render={history => (
<Account history={history} user={this.props.user} />
)}
/>
<Route exact path="/home" component={UserHome} />
<Route exact path="/checkout/address"
component={CheckoutContainer}
/>
<Route exact path="/checkout/credit"
component={CheckoutContainer}
/>
<Route component={Products} />
</Switch>
)}
{/* Displays our Login component as a fallback */}
<Route component={Products} />
{/* <Redirect to="/products" /> */}
</Switch>
The text was updated successfully, but these errors were encountered:
You cannot nest <Switch>es. A <Switch> treats all of its direct children as <Route> element, so a <Switch> in a <Switch> will act as a pathless <Route>.
One alternative approach would be to have two <Switch>es and render one or the other based on if the user is logged in. This isn't perfect because it requires you to duplicate some of your routes.
{isLoggedIn
? <Switch>{/* all routes */}</Switch>
: <Switch>{/* public routes */</Switch>}
If it were me, I would probably write a custom <Switch> component that is better suited for this use case. It is really just a loop over props.children, so implementing your own isn't very difficult.
Version
react-router-dom 4.1.1
Hello,
Ran into an issue when trying to nest Switches for these routes.
Going to a route that is contained inside the inner Switch it will redirect to
/products
if I was usingRedirect
. To try to work around that I replaced Redirect with a fallback route, but this solution only works ifisLoggedIn
is false so to fix that I also added a fallback route inside the inner Switch.But this doesn't seem right. Is there a better way to implement this? This is my first time submitting an issue please excuse my lack of formatting.
The text was updated successfully, but these errors were encountered: