@eureca/eureca-ui
Version:
UI component library of Eureca's user and admin apps
71 lines (62 loc) • 1.68 kB
JavaScript
import React, { useState, useMemo, useCallback } from 'react';
import PropTypes from 'prop-types';
import styled from 'styled-components';
import { FaStar, FaRegStar } from 'react-icons/fa';
import { Flex } from '../Flex';
import { colors } from '../../theme/colors';
const StarsWrapper = styled.div`
display: flex;
flex-direction: row;
& div {
margin: 0 4px;
}
& div:first-child {
margin-left: 0;
}
& div:last-child {
margin-right: 0;
}
`;
function Rating({ maxRating, selected, onChange, ...props }) {
const callback = useCallback(onChange, [onChange]);
const [rating, setRating] = useState(selected);
const stars = useMemo(() => {
const handleChange = rating => {
setRating(rating);
callback(rating);
};
return Array.from({ length: maxRating }, (u, i) => (
<Flex alignCenter justifyCenter key={`rating-${i}`}>
{i < rating ? (
<FaStar
key={`star-${i}`}
size={36}
color={colors.green1}
style={{ cursor: 'pointer' }}
onClick={() => handleChange(i + 1)}
/>
) : (
<FaRegStar
key={`star-${i}`}
size={36}
color={colors.gray3}
style={{ cursor: 'pointer' }}
onClick={() => handleChange(i + 1)}
/>
)}
</Flex>
));
}, [maxRating, rating, callback]);
return <StarsWrapper {...props}>{stars}</StarsWrapper>;
}
Rating.propTypes = {
maxRating: PropTypes.number,
selected: PropTypes.number,
onChange: PropTypes.func,
};
Rating.defaultProps = {
maxRating: 5,
selected: 0,
onChange: () => {},
};
export { Rating };