Tips for keeping the hover effect of a sibling element in Material-UI

Card Component

import image from "../../Assets/pic.jpg";
import React, { useState } from "react";
import { makeStyles } from "@material-ui/core/styles";
import Card from "@material-ui/core/Card";
import CardActionArea from "@material-ui/core/CardActionArea";
import FavoriteBorderIcon from "@material-ui/icons/FavoriteBorder";
import CardContent from "@material-ui/core/CardContent";
import CardMedia from "@material-ui/core/CardMedia";
import Typography from "@material-ui/core/Typography";
import styles from "./Cards.module.css";
import Stars from "../Stars/Stars";

const useStyles = makeStyles({
  root: {
    maxWidth: 345,
  },
});

const Cards = () => {
  const [showComponent, setShowComponent] = useState(false);
  const classes = useStyles();

  const handleToggleHoverIn = (event) => {
    event.preventDefault();
    setShowComponent(true);
  };

  const handleToggleHoverOut = (event) => {
    event.preventDefault();
    setShowComponent(false);
  };

  console.log("The state showComponent value is ", showComponent);

  return (
    <div className={styles.container}>
      <Card
        onMouseEnter={handleToggleHoverIn}
        onMouseLeave={handleToggleHoverOut}
        className={classes.root}
      >
        <CardActionArea>
          <div id={styles.imageCentre}>
            <CardMedia
              component="img"
              alt=""
              className={styles.image}
              image={image}
              title="Contemplative Reptile"
            />

            {/*
            here when I hover over my <Stars/> and  <FavoriteBorderIcon/>, the hover effect of opacity that I have on
            my Card's image, vanishes
             */}
            {showComponent ? (
              <>
                <div id={styles.stars}>
                  <Stars />
                </div>
                <FavoriteBorderIcon fontSize="large" id={styles.heart} />
              </>
            ) : null}
          </div>
          <CardContent>
            <Typography
              gutterBottom
              variant="h5"
              component="h2"
              id={styles.textCentre}
            >
              Printed round Neck
            </Typography>
            <Typography variant="body2" color="textSecondary" component="p">
              <div class="text">
                <p id={styles.price}>
                  <b>Rs. 454</b>
                  <strike>Rs. 699</strike>
                  <span style={{ color: "#FF7F7F" }}> (35 % off) </span>
                </p>
              </div>
            </Typography>
          </CardContent>
        </CardActionArea>
      </Card>
    </div>
  );
};

export default Cards;

Card's Styling in CSS

.image {
  width: 300px;
  justify-content: center;
}

.image:hover {
  opacity: 0.5;
}

#imageCentre {
  align-items: center !important;
  position: relative;
}

/* #imageCentre:hover {
  opacity: 0.5;
} */

#textCentre {
  text-align: center;
}

.container {
  display: flex;
  justify-content: center;
  padding: 2em;
}

#price,
.text h3 {
  text-align: center;
}

#price b {
  padding-right: 0.5em;
  font-size: 1.3em;
}

#heart {
  position: absolute;
  top: 0;
  right: 0;
  padding: 20px 20px 0 0;
  color: aliceblue;
}

#stars {
  position: absolute;
  top: 50%;
  left: 50%;
  margin-right: -50%;
  transform: translate(-50%, -50%);
  margin-top: 50%;
}

When hovering over the card, the opacity hover effect appears, but as soon as I move to the heart or star component, the opacity hover effect disappears. Is there a way to keep the opacity hover effect even when hovering over the stars and heart components?

Live Link

Answer №1

If you're looking for a way to accomplish this, here's an example that may help. The key point in this solution is utilizing the :hover pseudo-class on a common parent of the image, stars, and icon elements. In the provided code snippet, this is achieved by using the action class on the CardActionArea element. While my example utilizes makeStyles, you can achieve the same outcome in CSS with the following code:

#imageCentre:hover .image {
  opacity: 0.5;
}

It seems like you attempted something similar based on the commented-out #imageCenter:hover styles. However, since you didn't specify the descendant .image class for the opacity, it affected the stars and favorite icon as well, which may not have been your intention.

Below is a complete working example:

// Import necessary modules/components
// Define styles using makeStyles from Material-UI
// Implement MediaCard component

const useStyles = makeStyles({
  // Define style classes for various elements
});

export default function MediaCard() {
  const classes = useStyles();

  return (
    <Card className={classes.root}>
      <CardActionArea className={classes.action}>
        // Content within CardActionArea 
      </CardActionArea>
      <CardActions>
        // Buttons or actions within CardActions
      </CardActions>
    </Card>
  );
}

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

retrieving information from GraphQL for use in React applications

After cloning this React dashboard and modifying it to suit my requirements, I wanted to retrieve data from graphql and present it in a table (including orders and products tables). Specifically discussing the orders section, when a user clicks on a button ...

Step-by-step guide to creating a transition effect when the input changes

I'm looking to add a unique effect to my dropdown menu My goal is to create an effect in which the placeholder moves up and the new value seamlessly takes its place, using JS, jQuery, CSS, and HTML. View before transition View after transition ...

Tips for incorporating unique styles to a component in ReactJS

Struggling to apply unique styles to a React Next.js component? Below is the code snippet for a button component: import styles from "./button.module.css"; const Button = props =>{ return( <div> <button className={styles.button}>{ ...

Is the width set to fill the entire partial screen?

I'm facing a dilemma: I want the darkest-gray bar at the bottom right (visible after running the code below) to stretch as far as the browser window allows without encroaching on the light-gray section on the left. Here's the code snippet: <d ...

Step by step guide on how to connect a stylesheet in CSS

Hey there, I recently attempted to link a style sheet in my HTML for the first time. Unfortunately, I encountered an issue where it didn't work. Here's the code I used: <link href="css/StyleSheet.css" rel="stylesheet" type="text/css" /> W ...

Include a legal disclaimer on a website comprised of individual pages

The website at was uniquely crafted by hand, without the use of platforms like Wordpress or any PHP-type databases. Upon its creation over 15 years ago, a legal notice was not initially included on the website. Now, there is a desire to add a link to a l ...

JavaScript code to make titles slide in as the user scrolls

Looking for a better way to make all titles slide in upon scrolling instead of coding individually? Consider using a forEach loop! Here's how you can modify the code below: function slideInLeft() { document.querySelectorAll('.subtitle-left ...

Is it better to store JSON data locally using cookies or HTML5 local storage?

Currently, I am working on developing a mobile website using jquery mobile. My main concern right now is how to efficiently carry JSON data across multiple pages. I am debating whether it would be better to store this JSON data in a cookie or use HTML5 loc ...

The `innerHTML` function is responsible for closing HTML

My switch structure is set up as follows: switch (ratio) { case "16:9": imgContainer.innerHTML = '<img src="images/test-rata-de-aspect.jpg">' break case "4:3": imgContainer.innerHTML = '<img src="image ...

Utilize a generic data type for a property that can accept values of type 'number', 'string', or 'undefined'

This query involves React code but pertains to typescript rather than react. To simplify, I have a component called MyList which accepts a single generic type argument passed to the props type. The generic type represents an object that will be used to c ...

JavaScript: Transforming binary information from Uint8Array into a string causing file corruption

In my attempt to send a video file to a server in chunks using a basic jQuery $.ajax call, I followed these steps: Utilized the slice() method on the file object to extract a chunk Used FileReader.readAsArrayBuffer to read the generated blob Generated a ...

Utilizing MEAN.js for uploading images

Following a tutorial on the MEAN stack, I am looking to implement an image upload feature using MongoDB on a server. Resources: Angular directive for file uploads create-spot.client.view.html <div data-ng-controller="SpotsCreateController"> &l ...

What are the consequences of altering the DOM in React?

As a beginner react developer, I am currently working on creating a MERN App. I have a question for the community regarding my project where I needed to make several changes to the DOM as illustrated below: document.getElementsByTagName('body')[ ...

Issues with jQuery function arising post-update to newer jQuery version

Recently, I encountered an issue with a function that used to work perfectly fine with jQuery 1.8.3. However, when I upgraded to jQuery 1.10.x or above, the function stopped working. <script type="text/javascript"> $.ajaxSetup({cache: false}); ...

allowing absolutely positioned region to expand

For further information, please visit this page: test page In the process of designing a website, I have implemented a sidebar featuring an accordion style vertical navigation bar. The sidebar is set to be absolutely positioned in relation to its containi ...

Uploading my application on multiple servers after making changes using AngularJS and PHP

Currently, I am working on an angular-php web application that is live online for multiple users, each on their own subdomain. These subdomains include: sub1.mydomain.com sub2.mydomain.com sub3.mydomain.com sub4.mydomain.com sub5.mydomain.com Issue: An ...

Using a Do/While loop in combination with the setTimeout function to create an infinite loop

Having trouble with this script. The opacity transition works fine, but there seems to be an issue with the loop causing it to run indefinitely. My goal is to change the z-index once the opacity reaches 0. HTML <div class="ribbon_services_body" id="ri ...

Managing the state of a flag: communicating between Angular2 header and sidebar components

In my Angular2 project, I was working on a layout folder where I divided common layouts of certain pages into three components: header, sidebar, and footer. There was an anchor tag in the header that, when clicked, needed to extend the header to the left e ...

Troubleshooting Firebase functions that end with socket hang up error ECONNRESET

For the past two years, my Firebase Function has been successfully retrieving data from an external service with soap, parsing it, and sending it back to an Android app client. However, recently it suddenly stopped working without any changes on my part, g ...

Modifying button appearance based on state change in AngularJS

I have a button with a grey color and I want to create two different states for it: one that is selected (blue) and another that is in an idle state (grey). Currently, I am working on Angularjs but I am fairly new to this platform. Could you kindly provid ...