Currently, I am attempting to modify the color of a specific anchor link when it is hovered in React.
To achieve this, I have created two functions named handleMouseEnter
and handleMouseLeave
:
handleMouseEnter() {
this.setState({ isMouseInside: true });
}
handleMouseLeave() {
this.setState({ isMouseInside: false });
}
I then defined the linkstyle
as follows:
let linkStyle;
if (this.state.isMouseInside) {
linkStyle = { color: '#6996FF', cursor: 'pointer', textDecoration: "none" };
} else {
linkStyle = { color:"#999D9F", textDecoration: "none" };
}
Subsequently, I integrated it into my HTML code:
<ul style={{listStyle:"none"}} color={this.state.isMouseInside ? '#999D9F' : 'white'}
className="footer-links">
<li>
<a style={linkStyle} onMouseEnter={this.handleMouseEnter}
onMouseLeave={this.handleMouseLeave} href="#/category/1">
Pants
</a>
</li>
<li>
<a style={linkStyle} onMouseEnter={this.handleMouseEnter}
onMouseLeave={this.handleMouseLeave} href="#/category/2">
Shirts
</a>
</li>
<li>
<a style={linkStyle} onMouseEnter={this.handleMouseEnter}
onMouseLeave={this.handleMouseLeave} href="#/category/3">
Dress
</a>
</li>
<li>
<a style={linkStyle} onMouseEnter={this.handleMouseEnter}
onMouseLeave={this.handleMouseLeave} href="#/category/4">
Shoes
</a>
</li>
<li>
<a style={linkStyle} onMouseEnter={this.handleMouseEnter}
onMouseLeave={this.handleMouseLeave} href="#/category/5">
Jackets
</a>
</li>
</ul>
All anchor links change color on hover because there is only one state variable isMouseInside
.
My question now is whether there is a more efficient way to accomplish this without having to define multiple variables and set the state for each anchor link individually?