DemCodeLines
DemCodeLines

Reputation: 1920

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?

Upvotes: 3

Views: 2366

Answers (2)

lastmaj
lastmaj

Reputation: 326

Another approach (I am not sure about this but I faced the same problem and this is how I fixed it, but I admit it's less cleaner than what Ori Drori proposed):

In your SideNav component :

import React from "react";
import {useLocation} from "react-router"

export const SideNav = (props) => {
  const location = useLocation();
  const show = !location.pathname.includes("login");

  return (
    <>
       {show && (<YourLoginComponentCode /> }
    </>
  )
}

Upvotes: 1

Ori Drori
Ori Drori

Reputation: 191976

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>
)

Upvotes: 6

Related Questions