implementing a smooth transition effect for image changes upon hover

I've been working on a React project where I created a card that changes its image when hovered over. I wanted to add a smoother transition effect to the image change using

transition: opacity 0.25s ease-in-out;
, but it doesn't seem to be working as expected.

Could someone help me understand what's going wrong with my code?
View image here

import React, { useState } from 'react';

import './Article.css';

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 already tried using the transition property

transition: opacity 0.25s ease-in-out;
. My goal is to have the first image fade away smoothly to reveal the second image with a seamless transition effect.

Answer №1

To start with, make sure to update probs to props. 😉

You won't be able to animate changes in the src prop of an img element using CSS directly, but there's a workaround you can implement.

Instead of using your img element, try this:

<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>

I created two img elements and assigned a data-visible prop to each with opposite values. The first one has also been given a style of position: absolute; so they overlap. Don't forget to add the necessary styles to your CSS file as well.

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



The first CSS class works its magic - it hides elements with the article__image class when their data-visible prop is set to false.

Answer №2

There seems to be a small error in your code - there is a typo in the class name used. You have specified the className as articale in your JSX code, but in the CSS it is named as article.

Perhaps fixing this issue will resolve your problem.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Tips for aligning a radio button and label on the same line without breaking the layout in HTML and CSS

I'm encountering a problem with positioning an HTML radio button alongside its label. When the label text is too lengthy, it ends up wrapping below the radio button instead of staying on the same line. Here is the html: <div class="form-check ...

The concept of an HTML pop-up message that hovers above the content

While working on my HTML form, I encountered an issue regarding the display of a warning message notifying users about the caps lock being on. Currently, the warning is shown correctly in a div located to the right of the text box. However, this div's ...

Difficulty in defining the header while using the submit hook in Remix 1.15

When I utilize the useSubmit hook to send a POST request, it appears that the header I specify is not being taken into account. Below is the code snippet for my submit function: submit('/dashboard/', { method: 'post', heade ...

Icon: When clicked, initiate a search action

I am looking to make the icon clickable so that it can be used as an alternative to pressing the "return key" for searching. Check out this bootply example at . You simply need to click on the magnifying glass icon and it will initiate the search. ...

What is the best way to initiate a TouchEvent in a qunit test being run by grunt using only vanilla JavaScript?

I have implemented callbacks for different touch events that require testing. For example, the 'touchstart' event utilizes touch coordinates to configure a class member: NavigationUI.prototype.touchStart = function(evt) { this.interacting = ...

Generating a new array based on the keys found in a collection of objects

My array structure is quite complex with multiple objects containing different properties. let arr = [ { id: 1, name: "tony", hatColor: "blue" }, { id: 2, name: "larry", hatColor: "red" }, { id: 3, name ...

Adjusting the height of a DIV element to suit the window dimensions

I am facing an issue with the following HTML code: <div id="subpageHeaderImageSection"> <div id="subpageHeaderLeft"> <span id="holdImageP"></span> <!--[if lte IE 10]><img id="igm" src="theImages/sub ...

Floating dropdown within a scrolling box

How can I ensure that the absolute positioned dropdown remains on top of the scrollable container and moves along with its relative parent when scrolling? Currently, the dropdown is displayed within the scrollable area. The desired layout is illustrated i ...

I encountered an issue while trying to integrate react-alert into my React application. An Uncaught Error was thrown, stating that objects are not valid as a React

I encountered the following error: react-dom.development.js:14748 Uncaught Error: Objects are not valid as a React child (found: object with keys {$$typeof, render}). If you meant to render a collection of children, use an array instead. in Unknown (c ...

Searching for a solution on how to retrieve data server-side in the newest version of Next.js? Attempted to use getStaticProps but encountering issues with it not executing

Currently tackling a project involving Django Rest Framework with Next.js, and encountering a roadblock while trying to fetch data from the API. Data is present at the following URL: http://127.0.0.1:8000/api/campaigns, visible when accessed directly. The ...

Is there a way to make two parallelograms overlap seamlessly and adjust in size automatically using HTML?

Recently delving into the world of HTML and CSS, I've set my sights on designing something unique involving parallelograms that adjust dynamically. My vision includes four overlapping parallelograms starting from the top at 25%, 50%, 75%, and finally ...

Having trouble getting HTML to render properly in React JS on localhost using Apache server

For the past week, I've been working on resolving an issue. I started by creating a React Application using: npm create react-app After that, I attempted to build it with: npm run build Everything seemed to go smoothly. I generated a build folder ...

What is preventing targeting a class in React?

I'm having trouble targeting className in react. I attempted to target it using div className="navbar"> and .navbar { align-items: center; } but it's not working. div{ display: block; background-color: rgb(211, 57, 57); ...

Tips on identifying HTML email input validation using JavaScript?

Just like when you can determine whether an input element with a required attribute was successfully validated, try using the following code: if($('input[type="email"]').val() && $('input[type="email"]').val().includes('@') & ...

How can I stop VSC from automatically inserting "require"?

Every time I edit certain JS files in VSC, it automatically inserts "require()" calls that I then have to delete. Is there a way to stop VSC from adding these lines with "require"? Appreciate any help, Didier ...

Is there Polyfill Compatibility for Custom Elements in Angular 9?

When it comes to polyfilling support for custom elements created with Angular, there are various recommendations available. This demo demonstrates that adding the following polyfill in polyfills.ts works: import '@webcomponents/webcomponentsjs/custo ...

Dropdownmenu without borders

I'm having an issue with the dropdown menu on my website - there are no borders showing. I've tried fixing it myself with no luck, so I could really use some help. As a beginner in web development, I don't have much knowledge about these thi ...

Utilizing type arguments in JSX components when applying withStyles

When working with React and material-ui, I am attempting to create a JSX component that can accept generic parameters while also utilizing the withStyles Higher Order Component (HOC) to inject styles. The initial approach looked something like this: cons ...

Server-side rendering or updating of React elements

One issue I am facing in my React app is that while all components can update themselves through the browser, a specific module called jenkins-api only functions when called server side. To retrieve the data and pass it into my template, I have utilized th ...

Retrieve user details from a NextJS application following a successful Keycloak authentication on a Kubernetes cluster

I've been attempting to retrieve the authenticated user information in my NextJS app after being redirected to it following a successful Keycloak login on a different tab located at localhost:8080/auth. The ingress (entry point) is responsible for ch ...