quiteAbeginner
quiteAbeginner

Reputation: 31

How not to display button on certain specific pages?

New to React here, how do I not show the button on certain specific multiple pages. The pages are /login, /signup, forgot-password.

App.js

const App = props => {
  let routes = (
    <Switch>
        <Route path="/login" component={Login}/>
        <Route path="/signup" component={SignUp}/>
        <Route path="/forgot-password" component={ForgotPassword}/>
    </Switch>

Navbar.js

const Navbar = props => {
    return(
       <button className="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarNav"
                    aria-controls="navbarNav" aria-expanded="false" aria-label="Toggle navigation">
                <span className="navbar-toggler-icon"/>
       </button>
    )

What I have tried:

 {window.location.pathname == '/login' ? null : <button className="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarNav"
                aria-controls="navbarNav" aria-expanded="false" aria-label="Toggle navigation">
                <span className="navbar-toggler-icon"/>
 </button>}

But this one works on only one page.

Upvotes: 0

Views: 35

Answers (1)

Goutham J.M
Goutham J.M

Reputation: 2194

Instead of using window.location.pathname use react-router-dom methods , props.history.location.pathname , you can write a function to check if the pathname is included , like below

// this function accepts two arguments , one is string and an array , array contains all the routes that need to be compared to and it will return a boolean value , which can be used to render the component

function checkIfPathExist(pathname="",checkArrayRoute=[]){

  if(checkArrayRoute.includes(pathname)){
      return true
  }
  return false
}

In component you can do

 {checkIfPathExist(window.location.pathname,['/login']) ? null : <button className="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarNav"
                aria-controls="navbarNav" aria-expanded="false" aria-label="Toggle navigation">
                <span className="navbar-toggler-icon"/>
 </button>}

or

{checkIfPathExist(props.history.location.pathname,['/login']) ? null : <button className="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarNav"
                aria-controls="navbarNav" aria-expanded="false" aria-label="Toggle navigation">
                <span className="navbar-toggler-icon"/>
 </button>}

Check this sandbox for ref

Edit amazing-kirch-40vr3

Upvotes: 2

Related Questions