Skip to content
Advertisement

Conditional display of component based on Route matching

I am looking to conditionally render a component based on the route (using React Router), and the component should return null if it matches any path pre-defined in an array or some sort of similar data structure, where I do not have to be reliant on a <Switch>/<Route> setup. Currently here is what I have but it is clearly inefficient and not robust at all.

const Component = (props) => {
    const path = props.location.pathname;

    const paths_to_hide = ["/path/to/something", "/path/to/A", "/path/to/B"];
    if (paths_to_hide.indexOf(path) != -1) return null;
    
    return (
        <div>test</div>
    );
}

For example, if I want to match the following paths:

  1. /path/to/something
  2. /path/to/something/<any path that follows after this>
  3. /path/<random string>/fixed
  4. /newPath/<random string>

Note that this list is not just limited to 4 items, which is why I’m trying to stray away from having inline <Route> matching as I’m looking for a more scalable approach which I can save in a config file and have imported as an array or some similar data structure.

Currently my implementation will only be able to identify the first item, and there is no way to match the subsequent items, using the indexOf() function. What would be the best way to accomplish this? Any help is appreciated, thank you!

Advertisement

Answer

So upon reading the React Router docs further, I found this. This is definitely the most ideal solution and I overlooked this initially.

const Component = (props) => {
    const path = props.location.pathname;

    const paths_to_hide = ["/path/to/something", "/path/to/A", "/path/to/B"];
    return (
        <Switch>
            <Route path={paths_to_hide}>
            </Route>
            <Route>
                <div>test</div>
            </Route>
        </Switch>
    );
}

So now I can create complex paths and don’t have to loop through an array to match them, as it’s taken care of by the Route component, and this is ideal because now I can import this array from a config file instead.

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement