CraZyDroiD
CraZyDroiD

Reputation: 7105

Changing CSS onClick in reactjs

I'm changing(updating) css of a css class when i click on a certain div like follows.

JS part

constructor() {
        super();

        this.state = {
            transform: 'rotateY(0deg)',
        };

        this.trait_select = this.trait_select.bind(this);

    }


    trait_select = (e) => {

        this.setState({

            transform: 'rotateY(180deg)'


        })

    }

html part

<div className="trait_box polaroid" onClick={this.trait_select}>
    <div className="main_trait_card" style={{transform: this.state.transform}}>
    </div>
</div>

Now this piece of code work fine. But i want to change the css into transform: 'rotateY(0deg)' if the user clicks on trait_select again. How can i do that?

Upvotes: 0

Views: 2551

Answers (1)

Hieu Pham
Hieu Pham

Reputation: 6707

We just change a little like:

trait_select = (e) => {
  const newTransform = this.state.transform == 'rotateY(180deg)' ? 'rotateY(0deg)' : 'rotateY(180deg)';
  this.setState({
    transform: newTransform
  })
}

It will toggle the value when trail is selected!

But I'd like to store transform enabled/disabled instead. So it would be:

constructor

this.state = { rotated: false };

trait_select

this.setState({ rotated: !this.state.rotated });

html part

<div className="trait_box polaroid" onClick={this.trait_select}>
    <div className="main_trait_card" style={{transform: this.state.rotated ? 'rotateY(180deg)' : 'none' }}/>
</div>

Upvotes: 1

Related Questions