Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Don't render component on specific route

I have a React-based web application that utilizes React Router to map pages to different URLs:

export const Container = () => (
    <div>
        <SideNav/>
        <div>
            <Switch>
                <Route path="/login" component={LoginView} />
                <Route path="/route1" component={RouteOne} />
                <Route path="/route2" component={RouteTwo} />
            </Switch>
        </div>
    </div>
)

When any route gets hit, the sidebar gets rendered as well as the appropriate view. However, I am trying to build the layout such that for certain routes (such as "login"), the SideNav doesn't get rendered and the component (in this case, LoginView) is the only thing that gets rendered. In other words, LoginView should take over the div and be the only child of the top div.

Is there anyway this can be done?

like image 831
DemCodeLines Avatar asked Sep 08 '26 11:09

DemCodeLines


1 Answers

According to react-router docs:

path: string Any valid URL path that path-to-regexp understands.

path-to-regexp understand a string, array of strings, or a regular expression.

Array of routes:

State which routes will render the SideNav as well (Working Example):

  <Route path={['/route1', '/route2']} component={SideNav} />

RegExp:

Another option is to show the SideNav only if the path doesn't contain a certain word (working example):

  <Route path={/^(?!.*login).*$/} component={SideNav} />

And in your code:

export const Container = () => (
    <div>
        <Route path={['/route1', '/route2']} component={SideNav} />
        <div>
            <Switch>
                <Route path="/login" component={LoginView} />
                <Route path="/route1" component={RouteOne} />
                <Route path="/route2" component={RouteTwo} />
            </Switch>
        </div>
    </div>
)
like image 183
Ori Drori Avatar answered Sep 10 '26 23:09

Ori Drori