ttmt
ttmt

Reputation: 4984

React - Add class along with Dynamic class

I have a simple React button that toggles a class name on and off.

But how can I add other classes like

<div className={this.state.active ? this.state.feature : null} "another-class">

I could add them instead of null but I want the class on top of the toggle class

export default class Feature extends React.Component {

  state = {
    feature: this.props.otf,
    active: false,
  }

  toggleClass = () => {
    const currentState = this.state.active;
    this.setState({ active: !currentState });
  };

  render() {
    return (
      <div className="feature">
        <button onClick={this.toggleClass} ></button>

        <div className={this.state.active ? this.state.feature : null} >

        </div>

      </div>
    )
  }
}

Upvotes: 2

Views: 66

Answers (3)

Sugumar K
Sugumar K

Reputation: 204

Hi please check this method.

render() {
    let button_name = "class";
    if(this.state.active) {
       button_name = "active class";
    }
    return (
      <div className="feature">
        <button onClick={this.toggleClass} ></button>
        <div className={button_name} >
        </div>
      </div>
    )
  }

Upvotes: 0

Prijesh Meppayil
Prijesh Meppayil

Reputation: 540

Try like this:

<div className={"another-class " + (this.state.active ? this.state.feature : "")} >

You can move the "another-class" anywhere(LHS or RHS)

Upvotes: 1

Alberto Perez
Alberto Perez

Reputation: 2922

You can do the following:

<div className={`${this.state.active ? 'is-active': ''} class1 class2 class3`}>Content</div>

Upvotes: 3

Related Questions