0
votes

I am using material ui with react I want to know that How can I change the background color of my card component when a user hovers?

Here is my live code link in codeasandbox.

Below I also put my code.

MyCard.js Here I want to change the background color on hover so the padding area changes the color

import React from "react";
import { makeStyles } from "@material-ui/core/styles";
import Card from "@material-ui/core/Card";
import CardActionArea from "@material-ui/core/CardActionArea";
import CardMedia from "@material-ui/core/CardMedia";

const useStyles = makeStyles((theme) => ({
  root: {
    // maxWidth: 345,
    margin: theme.spacing(0.5),
    padding: theme.spacing(0.8),
    borderRadius: theme.spacing(0),
    "& :hover": {
      backgroundColor: "green"
    }
  },
  media: {
    height: 140
  }
}));

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

  return (
    <Card className={classes.root} elevation={3}>
      <CardActionArea>
        <CardMedia
          className={classes.media}
          image="https://images.pexels.com/photos/2787341/pexels-photo-2787341.jpeg?auto=compress&cs=tinysrgb&dpr=2&h=650&w=940"
          title="Face"
        />
      </CardActionArea>
    </Card>
  );
}

2
Remove the space after &Y.S.
Thank you! Oh my god, it was a typo and I was like what is going on? :-puser9824674

2 Answers

1
votes

You should try omitting that space in on hover property, and write "&:hover" rather than "&(space):hover". It works fine in your sandbox code.

0
votes

With the help of Y.S. I figured out it was just a typo having extra space near & Here is the working code

import React from "react";
import { makeStyles } from "@material-ui/core/styles";
import Card from "@material-ui/core/Card";
import CardActionArea from "@material-ui/core/CardActionArea";
import CardMedia from "@material-ui/core/CardMedia";
import { Paper } from "@material-ui/core";

const useStyles = makeStyles((theme) => ({
  root: {
    // maxWidth: 345,
    margin: theme.spacing(0.5),
    padding: theme.spacing(0.8),
    borderRadius: theme.spacing(0),
    "&:hover": {
      backgroundColor: "green"
    }
  },
  media: {
    height: 140
  }
}));

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

  return (
    <Card className={classes.root} elevation={3}>
      <CardActionArea>
        <CardMedia
          className={classes.media}
          image="https://images.pexels.com/photos/2787341/pexels-photo-2787341.jpeg?auto=compress&cs=tinysrgb&dpr=2&h=650&w=940"
          title="Face"
        />
      </CardActionArea>
    </Card>
  );
}