Louis Choicer
Louis Choicer

Reputation: 23

How do I change the css of classes through react dynamically

My question is regarding changing the CSS of classes through another class. I'm aware that I can only change the CSS if the element we're trying to change is adjacent or a sibling of the selected element.

My goal is to change the background color of the header and tabs class when the Link 'Bloody Mary' is selected but I don't know how to accomplish this. I am using React and the way I thought about it was using states. The default would be white and when the Bloody Mary link is active, it would change the state from white to black. I also plan on changing other styles like the font color but the main idea remains the same, changing the styling dynamically through react.

I have stripped my code to the basics so it looks cleaner. If you can offer some help it would be appreciated.

  class Header extends React.Component {
    render () {
        return(
          <div>
            <div className='header'>         
              <li className='tabs'><NavLink className='style' 
              activeClassName='selected'>Home</NavLink></li>

              <li className='tabs'><NavLink className='style' 
              activeClassName='selected'>Team</NavLink></li>

              <div className='dropdown'>
                <div className='tabs'><NavLink className='style projectstab' 
                activeClassName='selected'>Projects</NavLink></div>
                <div className='dropdown-content'>
                  <a>
                    <p className='dropdown-li'>
                    </p>
                    <NavLink activeClassName='bloodyselected'>
                      Bloody Mary
                    </NavLink>
                  </a>
                </div>
              </div>

              <li className='tabs'><NavLink className='style' 
              activeClassName='selected'>Contact Us</NavLink></li>
            </div>
      )
    }
  }

Upvotes: 2

Views: 4718

Answers (1)

ichigolas
ichigolas

Reputation: 7725

The className and style directives accepts interpolation of a dynamic value. You can use this to achieve what you want.

class Hello extends React.Component {
  constructor(props) {
    super(props);
    this.state = { style: {} };
    this.bloodyMary = this.bloodyMary.bind(this);
  }

  bloodyMary() {
    this.setState({
      style: { backgroundColor: 'red' },
      class: 'someclass'
    });
  }

  render() {
    return <div style={this.state.style} className={this.state.class}>
      <a onClick={this.bloodyMary}>Bloody Mary</a>
    </div>;
  }
}

Take a look at the online demo

Upvotes: 1

Related Questions