reusable star rating component in react

Solutions on MaxInterview for reusable star rating component in react by the best coders in the world

showing results for - "reusable star rating component in react"
Lya
26 Aug 2018
1import {
2  Box,
3  createStyles,
4  Grid,
5  Input,
6  makeStyles,
7  Theme,
8  FormHelperText
9} from '@material-ui/core';
10import React from 'react';
11import StarIcon from '@material-ui/icons/Star';
12import clsx from 'clsx';
13
14//---------------------------------------------------
15const useStyles = makeStyles((theme: Theme) =>
16  createStyles({
17    unCheckedIcon: {
18      color: 'grey',
19      fontSize: '50px'
20    },
21    poorRating: {
22      color: '#ff2824',
23      fontSize: '50px'
24    },
25    badRating: {
26      color: '#F7680C',
27      fontSize: '50px'
28    },
29    averageRating: {
30      color: '#FF9529',
31      fontSize: '50px'
32    },
33    goodRating: {
34      color: '#FDCC0D',
35      fontSize: '50px'
36    },
37    greatRating: {
38      color: '#FFDF00',
39      fontSize: '50px'
40    }
41  })
42);
43
44export default function StarRating({
45  register,
46  error,
47  helperText,
48  name
49}: {
50  register: any;
51  error: any;
52  helperText: any;
53  name: any;
54}) {
55  const classes = useStyles();
56  const [rating, setRating] = React.useState(0);
57  const [hover, setHover] = React.useState(0);
58
59  return (
60    <Grid item xs={12}>
61      <Box >
62        <div>
63          {[...Array(5)].map((s, i) => {
64            const ratingValue = i + 1;
65
66            return (
67              <label key={i}>
68                <Input
69                  type="radio"
70                  name={name}
71                  inputRef={register}
72                  error={error}
73                  hidden
74                  value={ratingValue}
75                  onClick={() => setRating(ratingValue)}
76                />
77                <StarIcon
78                  className={
79                    ratingValue <= (hover || rating)
80                      ? clsx({
81                          [classes.poorRating]: ratingValue === 1,
82                          [classes.badRating]: ratingValue === 2,
83                          [classes.averageRating]: ratingValue === 3,
84                          [classes.goodRating]: ratingValue === 4,
85                          [classes.greatRating]: ratingValue === 5
86                        })
87                      : classes.unCheckedIcon
88                  }
89                  onMouseEnter={() => setHover(ratingValue)}
90                  onMouseLeave={() => setHover(rating)}
91                  fontSize="large"
92                />
93              </label>
94            );
95          })}
96          {error && helperText && (
97            <FormHelperText error={true}>{helperText}</FormHelperText>
98          )}
99        </div>
100      </Box>
101    </Grid>
102  );
103}
104