LeBlaireau
LeBlaireau

Reputation: 17467

Reactsjs Hide button on certain paths

I have a header

const Header = () => (
  <header className="header">
    <h1 className="title">Sport shop</h1>
    <a href="/add" className="addBtn">Add a new shirt</a>
    <a href="/add" className="addBtn">back to homepage</a>
  </header>
);

This is a common component but once I am on the route '/addshirt' I only want to show the back button. Similarly when I am in the homepage I only want to show the 'add a new shirt button'

I am suing react router

  <Router>
        <div className="inner">
          <Header />
          <Route exact path="/" component={home} />
          <Route exact path="/addShirt" component={AddShirt} />
        </div>
      </Router>

Upvotes: 1

Views: 428

Answers (1)

Niekert
Niekert

Reputation: 947

You can use the same <Route /> component for this! It renders the passed component or render function only if the <Route /> matches the given path.

Try something like

const Header = () => (   
  <header className="header">
    <h1 className="title">Sport shop</h1>
    <Route exact path="/" render={() => <a href="/add" className="addBtn">Add a new shirt</a>} />
    <Route exact path="/addShirt" render={() => <a href="/add" className="addBtn">back to homepage</a>} />   
  </header> 
);

Also check out the docs for the Route component.

Upvotes: 1

Related Questions