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

ng-repeat not displaying any content

I am trying to create a form where users can input extra information by adding new rows, but I am struggling with generating the first row <div ng-repeat="row in rows"> <input type="text" placeholder="name"><input type="tel" placeholder="te ...

Empty value for $_POST variable following xmlhttp request

When my code makes an xmlhttp request to a php file with an ID for record deletion from the database, I encounter an issue. The error message 'comicID' is undefined shows up when attempting to delete. This signifies that the variable containing t ...

Refresh an iframe smoothly and without any visual distraction (using JavaScript)

Does anyone have a clever solution to dynamically refresh an iframe without the annoying flickering or flashing that usually occurs when the page reloads? Is it possible to incorporate a smooth blur-out and blur-in animation instead of the unappealing flic ...

What is the correct method for replacing a static page with an "outdated page"?

My website features several static promotional pages. However, I am facing the challenge of displaying an expired page once a promotion has passed. How can I achieve this seamlessly with static pages in NextJS? On my first attempt, I checked for expiratio ...

The length of the scope variable generates an error

var example = $scope.newgoal.gTitle; console.log(example.length); Even running this short code test, it throws an error message: TypeError: Cannot read property 'length' of undefined I've attempted to find various solutions without succes ...

Navigate to Angular Link using Scope Data

I have the user's GPS location, which is not fixed. From the frontend, I need to open it as a Google Maps link. <a href="#" ng-click='window.open("https://www.google.com/maps/place/{{data.usergps}}", "_system", "location=yes"); return false;& ...

Transferring an object from Javascript to C++/CX following a C++/CX interface in Windows Runtime Components

As a newcomer to Windows Runtime Component, I've been exploring ways to accomplish the following task. I'm looking to extend a C++ interface in JavaScript. namespace MySDK { public interface class LoggerPlugin { public: virt ...

The feature of determining if an edge exists, within the dagre-d3/graphlib,

Has anyone utilized the graph.hasEdge function in dagre-d3/graphlib to check for the existence of an edge between two nodes? This API takes two arguments representing the two nodes and verifies if there is an edge connecting them. I am facing an issue whe ...

A new value was replaced when assigning a JSON value inside a loop

Is there a way to generate a structure similar to this? { "drink": { "2": { "name": "coke", "type": "drink" }, "3": { "name": "coke", "type": "drink" } }, "food": ...

Why does the activeClassName of my React Router NavLink for the path '/' persist even after navigating to another page?

My navbar currently consists of three different components/links, laid out in the following structure: <ul className="flex text-white flex-col lg:flex-row list-none lg:ml-auto"> <NavLink activeClassName="active" ...

Issue with onclick event not being triggered by Javascript function inside constructor

My current challenge involves implementing a function called makeHighlight within the SmartButton constructor. The purpose of this function is to execute whenever I click on the SmartButton object, which is represented by an image element. To achieve thi ...

Exploring the combination of React and Redux by testing the dispatching of actions within other

Currently, I am using redux in a react application along with a thunk middleware. Within my codebase, there is a specific method that looks like this: export function login(username, password) { return function (dispatch, getState) { dispatch ...

The Angular Google Maps Module fails to initialize

After updating angular-google-maps to version 2.0.1 via bower and adding the required dependencies (bluebird, jquery, loadash), I noticed that my app works fine when I comment out google-maps. This suggests that the issue lies with angular-google-maps. He ...

ZeroClipboard intricate CSS issue

I have a list of images with an option box that appears on mouseover. The box contains an embedded code input field for copying purposes. I recently implemented zeroclipboard to enable the copy function on click. However, when I hover over an image and try ...

Utilizing a modular perspective in JavaScript to load JSON files as a view

I've been working on implementing a modular view approach for retrieving data from a JSON file in my JavaScript code, but I'm facing some issues. The snippet of code where I am trying to load the JSON file is contained within a separate JS file a ...

Troubleshooting Issue with Query Functionality in MEAN App's Find Request

I'm facing some challenges while working with queries in my MEAN App. Specifically, I am attempting to retrieve data that matches the input entered into a search field: $scope.searchInput = function(search){ $http({ method: 'GET', url: ...

The property linerGradiant of r cannot be destructured because it is not defined

I encountered the error "Cannot destructure property linerGradiant of r as it is undefined" during runtime, making it difficult to debug. The issue seems to stem from the compiled JS file, which is hard to read. The function is defined as follows: functio ...

What are the steps to fix a timeout error with React.js and socket.io acknowledgements?

My setup includes a Node.js server and a React.js client application. Data is exchanged between them using socket.io, but I'm running into an issue with implementing acknowledgment. Whenever I try to implement acknowledgment, I receive a timeout error ...

Combining package.json commands for launching both an Express server and a Vue app

I recently developed an application using Vue.js and express.js. As of now, I find myself having to open two separate terminal windows in order to run npm run serve in one and npm start in the other. My ultimate goal is to streamline this process and have ...

How can I effectively organize REST backend API requests when using React?

As my colleagues and I collaborate on developing a full stack web application, we have chosen React as our frontend framework. Our project involves performing CRUD operations on multiple resources, which means creating various pages. In the past, I came a ...