简体   繁体   中英

React JS. NavLink activeClassName ICON, IMAGE

I have this

 <div className="menu-item G-flex G-align-center">
     <img src={cartIcon} alt="Shopping cart" />
        <NavLink
            onClick={this.closeBar}
            to="/cart"
            activeClassName="active-page"
        >
           Shopping Cart
       </NavLink>
  </div>

So when active link is /shopping-cart I want to change cartIcon to another image, how I can ?

If by active link you mean url location, maybe try this quick fix:

 <div className="menu-item G-flex G-align-center">
 <img src={window.location.href.split('/').reverse()[0] === 'shopping-cart' ? otherIcon : cartIcon} alt="Shopping cart" />
    <NavLink
        onClick={this.closeBar}
        to="/cart"
        activeClassName="active-page"
    >
       Shopping Cart
   </NavLink>

where otherIcon is shown if user navigated to www.url.com/shooping-cart . You should be careful for some edge cases like www.url.com/shooping-cart/ (notice the extra '/' at the end), which will default to cartIcon .

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