"react-router": "5.0.1",
<Switch>
<Route
component={TestComponent}
key={TestComponentPath}
path={TestComponentPath}
exact
/>
{
exampleCondition && (
<>
<Route
component={TestComponent2}
key={TestComponentPath2}
path={TestComponentPath2}
exact
/>
<Route
component={TestComponent3}
key={TestComponentPath3}
path={TestComponentPath3}
exact
/>
</>
)
}
<Redirect to={redirectUrl} />
</Switch>
Showed example Switch, Redirect use case.
Should redirect to the given redirectUrl path if no path is matched.
Acts like no Redirect has been provided at the end of switch. Problem is probably caused by React.Fragment that has been used inside Switch. Redirection works fine when it's removed.
https://codesandbox.io/s/react-router-tklng
All children of a
<Switch>should be<Route>or<Redirect>elements. Only the first child to match the current location will be rendered.
https://reacttraining.com/react-router/web/api/Switch/children-node
Because you are using Fragment, you are adding additional child that is not supported by Switch thus your code dont render.
you should switch your code as below which adds conditional route without using fragment:
<Switch>
<Route
component={TestComponent}
key={TestComponentPath}
path={TestComponentPath}
exact
/>
{ exampleCondition &&
<Route
component={TestComponent2}
key={TestComponentPath2}
path={TestComponentPath2}
exact
/> }
{ exampleCondition &&
<Route
component={TestComponent3}
key={TestComponentPath3}
path={TestComponentPath3}
exact
/> }
<Redirect to={redirectUrl} />
</Switch>
If you are worrying about repeating code you can add additional layer in your Route somewhat like below:
<Switch>
<Route
component={TestComponent}
key={TestComponentPath}
path={TestComponentPath}
exact
/>
{someCondition && [
<Route
component={TestComponent2}
key={TestComponentPath2}
path={TestComponentPath2}
exact
/>,
<Route
component={TestComponent3}
key={TestComponentPath3}
path={TestComponentPath3}
exact
/>
]}
<Redirect to={redirectUrl} />
</Switch>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With