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:
divwas passed a style object that has previously been mutated. Mutatingstyleis deprecated. Consider cloning it beforehand. Check therenderofSegment.
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):
- Is that answer the best way to implement a hover effect, or should I clone the component like the error suggests?
- How should I implement the answer into my current component? The structure can be changed if necessary.