Elijah Lucian Elijah Lucian -4 years ago 75
CSS Question

ternary operator not working for this.state react js

Trying to change my header background color (for a start, eventually i will change more with the style. ) by a click.

however it fails to work .

toggleHeader(){
var newState;
newState = "headerBig" ? "headerSmall" : "headerBig";
this.setState({
toggleHeader: newState
})


}

What i'm trying to change is my header className={this.state.toggleHeader}

Am I not doing this right?

console log keeps returning "headerSmall" after it changes once.

Fixed

I used this code to fix it...
added a state of "isHeaderBig" and i am toggling that too. seems like double the work,, but.

toggleHeader(){
var newState = (this.state.isHeaderBig ? "headerSmall" : "headerBig");
this.setState({
toggleHeader: newState,
isHeaderBig: !this.state.isHeaderBig
})
}

Answer Source
toggleHeader(){
var newState;
newState = this.state.toggleHeader === "headerBig" ? "headerSmall" : "headerBig";
this.setState({
toggleHeader: newState

})

this is the right way, "headerBig" is always true

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download