wtk219
wtk219

Reputation: 285

Having a conditional within a style class in React

I'm trying to change the background color of a div upon hover using React (however, I do not want to create an entirely new class for this). I recognize that my syntax is incorrect, but I couldn't find a "correct" way to do this. Here's my codepen:

http://codepen.io/grapefruit0/pen/pRyOGG?editors=1010

On line 37-42 you'll see the following snippet:

{
  if (hover){
      backgroundColor: "#b3ffff",

  }else{
      backgroundColor: "#b30000",
  }
}

where hover is defined as follows:

getInitialState(){
  return {hover: false};
}

mouseOver(){
  this.setState({hover: true});
}

mouseOut(){
  this.setState({hover: false});
}

Is there a proper way to do this?

Upvotes: 1

Views: 1134

Answers (3)

user1641172
user1641172

Reputation:

You have a few problems as far as i can see:

When extending react classes, you should set your initial state in the constructor:

constructor(...props) {
  super(...props)
  this.state = {
    hover: false
  }
}

You have defined mouseOut and mouseOver functions, but you have not mapped them to the div:

return(
  <div style={boxStyle} 
       onMouseOver={this.mouseOver} 
       onMouseOut={this.mouseOut}>
  </div>
)

this is the function not the class the way you are defining them, try using arrow functions if you want lexical this from the class:

  mouseOver = () => this.setState({hover: true});
  mouseOut = () => this.setState({hover: false});

It's usually advised to use the ternary javascript operator within curly brackets for JSX:

backgroundColor: this.state.hover?"#b3ffff":"#b300ff"

Working pen here: http://codepen.io/anon/pen/xgVywE?editors=1010

Upvotes: 0

Piotr Białek
Piotr Białek

Reputation: 2737

You can use conditional (ternary) operator:

const boxStyle = {
      margin: 5,
      width: 30,
      height: 30,
      backgroundColor: this.state.hover ? "#b3ffff" : "#b30000",
      display: "inline-block",
      textAlign: "center"
}

But i think the best way in this case will be use just CSS pseudo-class :hover

Upvotes: 1

The Reason
The Reason

Reputation: 7983

Use this.state.hover instead of simple hover

backgroundColor: this.state.hover ? "#b3ffff" : "#b30000"

Upvotes: 0

Related Questions