Reputation: 1091
I am trying to change color of one specific anchor link on hover in React.
I made two functions, handleMouseEnter
and handleMouseLeave
:
handleMouseEnter () {
this.setState({ isMouseInside: true });
}
handleMouseLeave () {
this.setState({ isMouseInside: false });
}
Then I defined linkstyle
like this:
var linkStyle;
if (this.state.isMouseInside) {
linkStyle = { color: '#6996FF', cursor: 'pointer', textDecoration: "none" };
} else {
linkStyle = { color:"#999D9F", textDecoration: "none" };
}
So in my HTML code I call it:
<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>
I know that all anchor links will change color when you hover on mouse because there is only one state of variable isMouseInside
.
So my question is: is it possible to solve this on some more efficient way without defining multiple variables and setting state of each variable for each anchor link?
Upvotes: 0
Views: 2354
Reputation: 2979
Links has a native hover event that you can easily use. Just give an id or class to the specific link and write your css:
// HTML
<a href="" id="linkid">Link</a>
// CSS
#linkid {
color: #999D9F;
text-decoration: none;
}
#linkid:hover {
color: #6996FF;
cursor: pointer;
text-decoration: none
}
If you are using styled-components, you can define this component:
const SpecialLink = styled.a`
color: #999D9F;
text-decoration: none;
&:hover {
color: #6996FF;
cursor: pointer;
text-decoration: none
}
`;
Upvotes: 1