Search code examples
reactjsroutesreact-routercomponentsshow-hide

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>

Solution

  • 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.