简体   繁体   中英

How to change class when component is not equal to home than add class in header component in react.js?

I want to add a class in the header component when the route is not home. My code is:

App.js

<BrowserRouter>
  <Header />
  <Route exact path="/" component={Home}/>
  <Route exact path="/shop" component={Shop}/>
  <Route exact path="/contact" component={Contact}/>
  <Footer />
</BrowserRouter>

Header.js component code:

 <div className="all-category (here add-class when route is not equal to home)">
  <h3 className="cat-heading"><i className="fa fa-bars" aria-hidden="true"></i>CATEGORIES</h3>
   <ul className="main-category">
    <li><a href="#">New Arrivals <i className="fa fa-angle-right" aria-hidden="true"></i></a>
      <ul className="sub-category">
         <li><a href="#">accessories</a></li>
         <li><a href="#">best selling</a></li>
         <li><a href="#">top 100 offer</a></li>
       </ul>
    </li>
   </ul>
  </div>

you can check props.history.location.pathname in the header component Also make sure to wrap the header component in withRouter eg:

const Header = props => {
  return <div className={props.history.location.pathname === '/anything' ? "YOUR_CLASS":""}>....</div>
}

export default withRouter(Header)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM