Ralph W
Ralph W

Reputation: 145

Conditionally enable Route in React

I have created an <Authorise /> component which renders either a 'yes' or 'no' prop based on a boolean 'allowed' prop.

export const Authorise = ({
  allow = false,
  yes = () => null,
  no = () => null
}) => (allow ? yes() : no());

<Authorise /> component works as expected however when I try to render a <Route />, only the first route is rendered and the rest of the <Route /> components are ignored.

Why is this happening? If I render the routes outside of the <Authorise /> component it works fine. Only when rendering the components via the <Authorise /> component does it not work and I can't work out why.

Check out my example to see the issue: CodeSandbox

Upvotes: 1

Views: 65

Answers (2)

Nikko Khresna
Nikko Khresna

Reputation: 1009

It's because of
https://reactrouter.com/web/api/Switch/children-node

All children of a <Switch> should be <Route> or <Redirect> elements. Only the first child to match the current location will be rendered.

If you're using a library but not playing by its rule, then something like this is what was expected to happen.

Upvotes: 1

Daniel Sindrestean
Daniel Sindrestean

Reputation: 1193

The issue is not with your Authorize function, but because of the Route Component which will only display when the path is matched. The second issue it with Switch which will make it that only the first matched route to be displayed

With Switch added the "/" path will always be hit since it's the first one. If you try to remove your Switch (or move the route with "/" at the end) and go to "/next" on your local dev then the /next route will be displayed

Upvotes: 0

Related Questions