I am trying to stop some behaviour based on a condition if a mouse is hovering over a particular react component in my app.
I can only find old answers referencing jQuery and JS vanilla. Is there another way to do this? Or is it not acceptable?
Here is the component I interested in determining if the mouse is over:
<ContentRightHandSide offset={bannerHidden ? 80 : 120}>
<ContentTitle>
Activity
<img
style={{
display: "inline",
position: "relative",
marginLeft: "20px",
width: "35px",
}}
src={calendarIcon}
/>
</ContentTitle>
{authStatus === "authenticated" ? (
<ShareLogs
linkShareLogs={activeShareLogs}
isBannerHidden={bannerHidden}
hovered={hoveredNode}
selected={selectedNode}
/>
) : (
<div style={{ position: "relative" }}>
<img
src={blurredScreenLinks}
style={{
fontSize: "24px",
position: "relative",
margin: "0 auto",
width: "100%",
}}
/>
<button
style={{
backgroundColor: "#F7F1FF",
color: "#35373B",
position: "absolute",
fontFamily: "lato",
left: "0",
right: "0",
marginLeft: "auto",
marginRight: "auto",
width: "320px",
top: "100px",
padding: "0px 20px",
display: "flex",
alignItems: "center",
borderRadius: "60px",
}}
onClick={handleSignInClick}
>
<img
style={{
display: "inline",
position: "relative",
width: "80px",
cursor: "pointer",
margin: "-5px",
}}
src={slackIcon}
/>
<span style={{ textAlign: "left" }}>
Lorem Ipsum
</span>
</button>
</div>
)}
</ContentRightHandSide>
CodePudding user response:
You can define hover events like this in React, similar to how you would handle onClick
.
<Component
onMouseEnter={handleSomething}
onMouseLeave={handleSomething}
/>
CodePudding user response:
There are a few ways you can determine if the mouse is currently over a React component, but how to "stop some behavior" depends on how your behavior runs.
If you can make your behavior dependent on some state variable, you can give the React component a handler that sets the state on onmouseenter
and onmouseleave
events:
const [isMouseOver, setIsMouseOver] = useState(false)
...
<ContentRightHandSide
onm ouseEnter={() => setIsMouseOver(true)}
onm ouseLeave={() => setIsMouseOver(false)}
offset={bannerHidden ? 80 : 120}
>
...
</ContentRightHandSide>
The handler you give to the component doesn't need to set a state variable either, it can perform whatever logic is needed to change your behavior.
This JSFiddle demonstrates that behavior in a class-based component.
The events you might be interested in: https://developer.mozilla.org/en-US/docs/Web/API/Element/mouseenter_event
There is a section about handling events in the official React docs that might give you more ideas.