damnitrahul
damnitrahul

Reputation: 150

Show only One Component on a Route and Hide All Others

I am Making an App it has a Side Bar which I am showing in all routes. I want to hide everything on Login and Register Routes and only show Login and Register forms. How can I achieve it?

Here's is how I have structured it out

<BrowserRouter>
      <BodyContainer>
        <SideBar />
        <div>
         <Header/>
          <Switch>
            <Route exact path="/" component={Dashboard} />
            <Route exact path="/create" component={NewInvoice} />
            <Route exact path="/invoices" component={Invoices} />
            <Route exact path="/settings" component={Settings} />
            <Route exact path="/invoice/:id" component={InvoiceDetails} />
          </Switch>
        </div>
      </BodyContainer>
    </BrowserRouter>

I want to hide everything inside BodyContainer and Show a new Login Page.

Upvotes: 0

Views: 57

Answers (2)

MrCode
MrCode

Reputation: 64526

You can check the pathname to decide whether or not to render:

<BrowserRouter>
      <BodyContainer>
        {
          ['/login', '/register'].indexOf(window.location.pathname) == -1 && <SideBar />
        }
        <div>
         <Header/>
          <Switch>
            <Route exact path="/" component={Dashboard} />
            <Route exact path="/create" component={NewInvoice} />
            <Route exact path="/invoices" component={Invoices} />
            <Route exact path="/settings" component={Settings} />
            <Route exact path="/invoice/:id" component={InvoiceDetails} />
          </Switch>
        </div>
      </BodyContainer>
    </BrowserRouter>

Another solution is to restructure your components such that the SideBar is included inside each component, which would give you the flexibility of choosing which components should show it.

Upvotes: 1

FarukT
FarukT

Reputation: 1668

you can simply handle it before rendering the main page like this code

render(){
    const isUserLoggedIn = false;
    const privateRoutes = 
    (   <>
            <Route exact path="/" component={Dashboard} />
            <Route exact path="/create" component={NewInvoice} />
            <Route exact path="/invoices" component={Invoices} />
            <Route exact path="/settings" component={Settings} />
            <Route exact path="/invoice/:id" component={InvoiceDetails} />
        </>
    );
    const publicRoutes = (
        <>
            <Route exact path="/" component={Login} />
            <Route exact path="/register" component={Register} />
            <Redirect to="/"/>
            <
        </>
    );

    const content = isUserLoggedIn ? privateRoutes : publicRoutes;

    return(
        <BrowserRouter>
            <BodyContainer>
                <SideBar />
                <div>
                <Header/>
                    {content}
                </div>
            </BodyContainer>
        </BrowserRouter>

    )
}

Upvotes: 1

Related Questions