I would like to create some sort of animation on hover for my gallery with using react hooks, but so far I am not successful.
Goal explanation:
I would like to achieve, that when I hover with mouse on image that has overlay on - it will first show text under the image, and after some time the text will disappear and image will delete the overlay - basically it will light up.
What I did so far:
I created some overlay on image which disappears on hover with help of CSS.
<Col
xs={6}
className="img-wrap"
onClick={() => setSelectedData(post)}
onMouseEnter={handleMouseEnter}
>
<img src={post.image} alt="random" />
<div className="overlay">
<div className="text">{post.name}</div>
</div>
{hover && selectedData === post && <h1>HOVER </h1>}
</Col>
And the CSS:
.img-wrap {
position: relative;
}
image {
display: block;
width: 100%;
height: auto;
}
.overlay {
position: absolute;
top: 0;
bottom: 0;
left: 0;
right: 0;
height: 100%;
width: 210px;
opacity: 0.5;
transition: 0.5s ease;
background-color: black;
}
.img-wrap:hover .overlay {
opacity: 0;
}
.text {
color: white;
font-size: 20px;
position: absolute;
top: 50%;
left: 50%;
-webkit-transform: translate(-50%, -50%);
-ms-transform: translate(-50%, -50%);
transform: translate(-50%, -50%);
text-align: center;
}
This works fine, but the hover effects is triggered immediately instead of some time as I wish and the text is not shown on hover but onClick.
I think the best is to use setTime() function, but I am not sure how to connect it with css.'
Here is my sandbox:
https://codesandbox.io/s/inspiring-poitras-5y3b1?file=/src/App.js
I removed the onClick, placed the setSelectedData in the onMouseEnter, added a setTimeout in there, and put your setHover in the timeout. I don't particularly like using setTimeouts, but this was a quick way to do what you were looking for.
<Col
xs={6}
className="img-wrap"
onMouseEnter={() => {
setSelectedData(post);
setTimeout(() => {
setHover(true);
}, 1000);
}}
onMouseLeave={() => setHover(false)}
>
In the css we need to lose the :hover psuedo selector, and add a class:
.img-wrap .overlay.fade {
opacity: 0;
}
Then on the overlay we need to make the fade class conditional:
<div className={"overlay" + (hover && post === selectedData ? " fade" : "")}>
https://codesandbox.io/s/quizzical-mayer-0si2d?file=/src/App.js:506-731
Or by animating the css opacity property with a delay then there's no need for the timeout.
.img-wrap .overlay {
opacity: 1;
transition: opacity 2s linear 1s; // where 1s is your delay
}
img-wrap:hover .overlay {
opacity: 0;
transition: opacity 2s linear 1s; // where 1s is your delay
}
More info about transition properties here: https://www.w3schools.com/css/css3_transitions.asp