I have a page that has tabs on it. When I navigate to the page on my app I push to the base app. Ie. "/profile".
This is my profile component, the page that gets called.
<Profile>
<Switch>
<Route exact path={`${path}/feed`} component={Feed} />
{profileId !== null && (
<>
<Route exact path={`${path}/friends`} component={Friends} />
<Route exact path={`${path}/locations`} component={Locations} />
<Route exact path={`${path}/blockedlist`} component={BlockedList} />
</>
)}
<Redirect from={path} to={`${path}/feed`} />
</Switch>
</Profile>
The redirect never gets run. When I remove the check if profileId !== null then it works. Basically when I load the page it will be at path /profile then this component should handle the redirect to /feed on initial load.
If you need to avoid wrapping an element (like with these Route's), you can spread an array of JSX elements instead, like this:
<Switch>
<Route exact path={`${path}/feed`} component={Feed} />
{...(profileId !== null ? [
<Route exact path={`${path}/friends`} component={Friends} key='friends' />,
<Route exact path={`${path}/locations`} component={Locations} key='locations' />,
<Route exact path={`${path}/blockedlist`} component={BlockedList} key='blockedlist' />
]: [])}
<Redirect from={path} to={`${path}/feed`} />
</Switch>
Broken down, what this is doing is:
{
...( // The spread operator will expand the array it's given into its components
conditional ? // Check your condition
[routes]: // If it's true, return the routes
[] // If not, return no routes
)
}
Since it's returning an array into the render function, each item should have a key (Which is used by react to optimise the re-renders) so I've set each route to have part of it's path name as the key as these should be unique.
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