Reputation: 35
Basically, on hover i am changing the text color of a link, I was able to achieve what i needed, however, this looks too much of code for me, I believe there should be a better way. I am wondering if there is a better logic than this. Please suggest.
class App extends React.Component {
constructor() {
super();
this.state = {
link_su: false,
link_si: false
};
}
componentDidMount() {
this.hover_signup = document.getElementById("signup");
this.hover_signin = document.getElementById("signin");
this.hover_signup.addEventListener("mouseenter", this.colorChange);
this.hover_signup.addEventListener("mouseleave", this._colorChange);
this.hover_signin.addEventListener("mouseenter", this.colorChange);
this.hover_signin.addEventListener("mouseleave", this._colorChange);
}
componentWillUnmount() {
//removing all event listeners.
}
colorChange = e => {
if (e.target.id == "signup") {
this.setState({ link_su: !this.state.link });
} else {
this.setState({ link_si: !this.state.link });
}
};
_colorChange = e => {
if (e.target.id == "signup") {
this.setState({ link_su: this.state.link });
} else {
this.setState({ link_si: this.state.link });
}
};
render() {
return (
<main role="main" className="inner cover">
<a
href="/signup"
className="btn btn-lg btn-secondary"
style={link_su ? { color: "white" } : { color: "#282c34" }}
id="signup"
>
Sign Up
</a>
<br />
<br />
<a
href="/signin"
className="btn btn-lg btn-secondary"
style={link_si ? { color: "white" } : { color: "#282c34" }}
id="signin"
>
Sign In
</a>
</main>
);
}
}
Upvotes: 0
Views: 75
Reputation: 15652
Yes there is an easier way, this can all be done with CSS using the :hover
selector.
For example:
a {
color: blue;
}
a.link1:hover {
color: red;
}
a.link2:hover {
color: yellow;
}
<a class="link1" href="">Link 1</a>
<a class="link2" href="">Link 2</a>
Edit:
If you use the style property to apply styles, I believe nothing (except !important
properties) can override that style, so if you provide the initial color through style but the hover color in a stylesheet, then the hover color will be overridden by the initial style and not show up. So it's best not to mix in-line and stylesheet styles.
Here's an example of what happens:
a.link1:hover {
color: red;
}
a.link2:hover {
color: red !important;
}
<a class="link1" style="color: blue;" href="">Always Blue</a>
<a class="link2" style="color: blue;" href="">Using Important (but you shouldn't)</a>
Note: I'm really not recommending using the !important
flag here, instead I'm recommending removing the in-line styles.
Upvotes: 5