Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Material-UI : Rating Component, change color based on value

Goal

To change color of Ratings ( a material-ui component ) based on the value during hover. For example if I hover on 1rst star, color becomes red, if on 5th star then it becomes green.

enter image description here

I've tried making a custom component which changes color on hover, like this -

const StyledRating = withStyles({
  root: {
    color: "#ff6d75",
  },
  iconFilled: {
    color: '#ff6d75',
  },
  iconHover: {
    color: '#fff',
    backgroundColor: "#000",
  },
})(Rating);  

But it changes all of the icons color.

Can anyone please guide me, how to change specific icons in ratings color based on the value I select or hover on.

Current sandbox link.

like image 656
Neha Avatar asked Aug 17 '20 13:08

Neha


Video Answer


1 Answers

You could use dynamic style (Overriding styles with classes)

const useStyles = makeStyles({
  root: {
    // ...
  },
  'icon-1': { color: 'red' },
  'icon-2': { color: 'coral' },
  'icon-3': { color: 'orange' },
  'icon-4': { color: 'skyblue' },
  'icon-5': { color: 'green' }
});

export default function HoverRating() {
  // ... 
  return (
    <div className={classes.root}>
      <Rating
        classes={{
          iconHover: classes[`icon-${Math.ceil(hover)}`]
        }}
        //...
      />
      ...
    </div>
  );
}

Edit Material demo (forked)

like image 174
hgb123 Avatar answered Sep 20 '22 00:09

hgb123