Sth
Sth

Reputation: 532

How to change styles of a parent element of a <NavLink> tag in React.js?

Navbar

I want to change the list-items' background-color property, when the chosen NavLink is active. From the docs I learned, that for adding an additional class to a NavLink, when it is active, I can use activeClassName prop, for making what I want, I need a parent selector in css, which don't exist.

How to choose the parent element of the NavLink tag, when it has an active class?

I need the green background only on the list-item with an active child NavLink.

<ul className="navbar-nav">
        <li className="navItem">
           <NavLink className="navlink text-dark" activeStyle={{color: "#fff !important"}} to="/" exact>about</NavLink>
        </li>
        <li className="navItem">
           <NavLink className="navlink text-dark" activeStyle={{color: "#fff !important"}} to="/services">services</NavLink>
        </li>
        <li className="navItem">
           <NavLink className="navlink text-dark" activeStyle={{color: "#fff !important"}} to="/contacts">contacts</NavLink>
        </li>
</ul>

Upvotes: 2

Views: 4164

Answers (1)

VoodooDS
VoodooDS

Reputation: 610

The most straight forward way would probably be to apply a state to your parent element to achieve this effect, which i.e. could represent the name of a CSS class for your parent. You can change this state depending on the active route or the clicked item to apply a new CSS class.

See working example here

Your parent class could look like this:

import React from 'react'
import NavLink from './NavLink'

class Navbar extends React.Component {
  constructor(props) {
    super(props)
    this.state = {
      navbarClass: "navbar"
    }
  }

  setBgClass (title) {
    this.setState({
      navbarClass: `navbar navbar-${title}`
    })  
  }

  render() {
    return (
      <div className={this.state.navbarClass}>

        <NavLink 
          className="nav-item" 
          onClick={() => this.setBgClass('about')} 
          href='/about/'>
            About
        </button>

        <NavLink 
          className="nav-item" 
          onClick={() => this.setBgClass('services')} 
          href='/services/'>
            Services
        </button>

        <NavLink 
          className="nav-item" 
          onClick={() => this.setBgClass('contact')} 
          href='/contact/'>
            Contact
        </button>

    </div>
    );
  }
}

export default Navbar

After that you only have to define appropriate CSS classes in your components stylesheet:

.navbar-about { background: green; }
.navbar-services { background: blue; }
.navbar-contact { background: orange; }

NOTE: If you call actual routes within your application i.e. using react-router, you may want to change the state of your parent navbar depending on your active route on componentDidMount instead of onClick, since the component may remount when the route changes.

Upvotes: 1

Related Questions