Phil
Phil

Reputation: 3562

How to implement hover effect without mutating style directly?

I have a React component that has an implemented hover effect, as such:

let style = {
  backgroundColor: "blue"
}

class someComponent extends React.Component{

  constructor(props){
    super(props)

    this.state = {
      hover: false
    }
  }

  handleHover(event) {
    this.setState({ hover: true });
  }

  handleExit(event) {
    this.setState({ hover: false });
  }

  render(){
    if(this.state.hover){
      style.backgroundColor = "red"
    } else {
      style.backgroundColor = "blue"
    }

    return(
      <Segment style={style} onMouseEnter={this.handleHover} onMouseLeave={this.handleExit} />
    );
  }
}

However, even though it does work, I get an error saying:

Warning: div was passed a style object that has previously been mutated. Mutating style is deprecated. Consider cloning it beforehand. Check the render of Segment.

I looked up the answer from this post, and it says to implement it this way:

const {styleFromProps} = this.props;

const newStyle = {...styleFromProps, marginTop: '45px'};

However, my style is defined outside of the class, and I'm not passing any styling down from the parent component. So I'm not too sure how to implement this answer into my current code.

Question(s):

Upvotes: 2

Views: 64

Answers (1)

Andrew Li
Andrew Li

Reputation: 57954

Just use the hover state to determine the style instead of storing it in a separate object. Because the background color depends on state, don't store it outside the component, tie it to state with a ternary operator:

<Segment style={{
  backgroundColor: this.state.hover ? 'red' : 'blue'
}} />

And if you have other styles, just use spread syntax:

<Segment style={{
  ...styleObj,
  backgroundColor: this.state.hover ? 'red' : 'blur'
}} />

This will copy all the styles you already have in styleObj then also apply background color. You can learn more about spread syntax in React JSX here.

Upvotes: 1

Related Questions