i working on a react project and i made a card with an image that changes when you hover over it and i would like to add a transition when the image changes to make it smother, itried using
transition: opacity 0.25s ease-in-out;
but it not working.
here is my code can someone help me
enter image description here
import React, { useState } from 'react';
import './Article.css';
// import Paper from '@mui/material/Paper';
function Article(props) {
const [isHovered, setIsHovered] = useState(false);
return (
<div
className='article'
onMouseEnter={() => setIsHovered(true)}
onMouseLeave={() => setIsHovered(false)}
>
<img
className='article__image'
src={isHovered ? props.hoverImage : props.image}
alt={props.title}
/>
<h3 className='article__title'>{props.title}</h3>
<p className='article__price'>{props.price}</p>
</div>
);
}
export default Article;
.article{
width: 100%;
height: 100%;
display: flex;
flex-direction: column;
align-items: center;
}
.article__image {
width: 100%;
height: 100%;
max-height: 250px;
object-fit:cover;
transition: opacity 0.25s ease-in-out;
}
i tried using transition property transition: opacity 0.25s ease-in-out;
i would like the first image to fade away and reveal the second image on something that make the transition somther
2
Answers
There is one issue with your code, you have a typo in the class name. You have added the className as
articale
in your JSX but in CSS you have named asarticle
.I think this might work.
First of all, you should change
probs
toprops
. 😉Change in img
src
prop cannot be animated in CSS, but you can use a small trick to achive what you want.Instead of your img element use:
So, I made 2 img elements and gave them a
data-visible
prop with opposite values. I’ve also addedposition: absolute;
to the first one so they stay on each other. Then you need to add this to your CSS file.The first class does the trick – it hides elements with the
article__image
class when theirdata-visible
prop is set to false.