简体   繁体   中英

Active NavLink with Reactstrap and React Router Dom

I'm building the navbar component for my application but I'm having problems with the activeClassName prop. It doesn't change any class or style when i change between the Links. I've tried everything I saw on Internet with no results. Maybe someone can give me an advice with this issue.

My imports:

import React from 'react';
import { NavLink as RRNavLink } from 'react-router-dom';
import { Nav, NavItem, NavLink } from 'reactstrap';

This is the code I have so far:

    <Nav className="navbar-logged">
      <NavItem>
        <NavLink
          className="nav-link-gdc"
          activeClassName="active"
          to="/home"
          tag={RRNavLink}
        >
            INICIO
        </NavLink>
      </NavItem>
      <NavItem>
        <NavLink
          className="nav-link-gdc"
          activeClassName="active"
          to="/secondLink"
          tag={RRNavLink}
        >
            secondLink
        </NavLink>
      </NavItem>
      <NavItem>
        <NavLink
          className="nav-link-gdc"
          activeClassName="active"
          to="/thirdLink"
          tag={RRNavLink}
        >
            thirdLink
        </NavLink>
      </NavItem>
    </Nav>

Thank You

A possible reason is that you are using Redux to manage application's state

https://github.com/reactjs/react-redux/blob/master/docs/troubleshooting.md#my-views-arent-updating-when-something-changes-outside-of-redux

If your views depend on global state or React “context”, you might find that views decorated with connect() will fail to update.

This is because connect() implements shouldComponentUpdate by default, assuming that your component will produce the same results given the same props and state. This is a similar concept to React's PureRenderMixin.

The fastest ( not the best ) solution for this is to pass the pure: false option to connect() function of the component that has your NavLink(s) (in my case it's the Header)

function mapStateToProps(state) {
  return { test: state.test}
}

export default connect(mapStateToProps, null, null, {
  pure: false
})(Header)

This will remove the assumption that Header is pure and cause it to update whenever its parent component renders. Note that this will make your application less performant, so only do this if you have no other option.

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