user3082488
user3082488

Reputation: 71

REACT : change button color when active does not work

I want my side bar button to change color when I route to its linked page. my code changes the color and the color remains the same even if I route to a different page. here is my code:

lass Sidebar extends Component<{}, {}> {
  style = this.getBtnClassName();
  render() {
    return (
      <aside className="sidebar">
        <nav className="nav">
          <LinkButton to="/timer" label="Timer" cssPrefix={this.getBtnClassName()} styles={['block']} />
          <LinkButton to="/reports" label="Report" cssPrefix={this.getBtnClassName()} styles={['block']} />
        </nav>
      </aside>
    );
  }
  getBtnClassName() {
    if (window.location.href === 'http://localhost:3000/timer') {
      return 'nav_active';
    } else {
      return 'nav__btn';
    }
  }
}

export default Sidebar;

Upvotes: 0

Views: 386

Answers (2)

David Zambrano
David Zambrano

Reputation: 658

you can use NavLink from react-router-dom and use the prop activeClassName

ref: https://github.com/ReactTraining/react-router/blob/master/packages/react-router-dom/docs/api/NavLink.md

Upvotes: 1

spd
spd

Reputation: 38

You can use className instead. Start out by simply making your getBtnClassname simply use the window.location.pathname and not the window.location.href, then it can also work when deployed to any website.

    getBtnClassName() {
    if (window.location.pathname === '/timer') {
      return 'nav_active';
    } else {
      return 'nav__btn';
    }
  }

From there, all you really need to do is call the function to assign the returned value of this.getBtnClassName to be a classname you wish to apply.

<button to="/timer" label="Timer" className={this.getBtnClassName()}>{this.getBtnClassName()}</button>

You could also assign the correct class to a variable inside the render, which when you only have 2 classes in your case is a little cleaner.

 const btnClass = window.location.pathname === "/timer" ? "nav_active" : "nav__btn"

<button to="/reports" label="Report" className={btnClass}>{btnClass}</button>

Example: https://stackblitz.com/edit/react-scltse

Upvotes: 1

Related Questions