skip to Main Content

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


  1. 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 as article.

    I think this might work.

    Login or Signup to reply.
  2. First of all, you should change probs to props. 😉

    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:

    <div className="article__image">
      <img
        data-visible={isHovered}
        className="article__image absolute"
        src={props.hoverImage}
        alt={props.title}
      />
      <img
        data-visible={!isHovered}
        className="article__image"
        src={props.image}
        alt={props.title}
      />
    </div>
    

    So, I made 2 img elements and gave them a data-visible prop with opposite values. I’ve also added position: absolute; to the first one so they stay on each other. Then you need to add this to your CSS file.

    .article__image[data-visible="false"] {
      opacity: 0;
    }
    .absolute {
      position: absolute;
    }
    
    

    The first class does the trick – it hides elements with the article__image class when their data-visible prop is set to false.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search