react-ratings-star
Version:
A simple React component to display ratings with decimal values (e.g., 4.5 stars).
68 lines (66 loc) • 2.39 kB
JavaScript
import React from "react";
// A single, reusable Star component using an SVG linearGradient for the partial fills
var Star = function Star(_ref) {
var fillPercentage = _ref.fillPercentage,
size = _ref.size,
fullColor = _ref.fullColor,
emptyColor = _ref.emptyColor;
// An unique ID for the gradient to avoid conflicts
var gradientId = "grad-".concat(Math.random());
return /*#__PURE__*/React.createElement("svg", {
height: size,
width: size,
viewBox: "0 0 24 24"
}, /*#__PURE__*/React.createElement("defs", null, /*#__PURE__*/React.createElement("linearGradient", {
id: gradientId
}, /*#__PURE__*/React.createElement("stop", {
offset: "".concat(fillPercentage, "%"),
stopColor: fullColor
}), /*#__PURE__*/React.createElement("stop", {
offset: "".concat(fillPercentage, "%"),
stopColor: emptyColor
}))), /*#__PURE__*/React.createElement("path", {
d: "M12 .587l3.668 7.429 8.207 1.192-5.938 5.787 1.401 8.17L12 18.897l-7.338 3.856 1.401-8.17L.125 9.208l8.207-1.192L12 .587z",
fill: "url(#".concat(gradientId, ")"),
stroke: fullColor,
strokeWidth: "1"
}));
};
// The main component for the export
var Rating = function Rating(_ref2) {
var _ref2$value = _ref2.value,
value = _ref2$value === void 0 ? 0 : _ref2$value,
_ref2$max = _ref2.max,
max = _ref2$max === void 0 ? 5 : _ref2$max,
_ref2$size = _ref2.size,
size = _ref2$size === void 0 ? 24 : _ref2$size,
_ref2$fullColor = _ref2.fullColor,
fullColor = _ref2$fullColor === void 0 ? "#FFD700" : _ref2$fullColor,
_ref2$emptyColor = _ref2.emptyColor,
emptyColor = _ref2$emptyColor === void 0 ? "#E0E0E0" : _ref2$emptyColor;
var stars = [];
for (var i = 1; i <= max; i++) {
var fillPercentage = void 0;
if (value >= i) {
fillPercentage = 100; // Star is completely full
} else if (value > i - 1) {
fillPercentage = (value - (i - 1)) * 100; // Star is partially full
} else {
fillPercentage = 0; // Star is completely empty
}
stars.push(/*#__PURE__*/React.createElement(Star, {
key: i,
fillPercentage: fillPercentage,
size: size,
fullColor: fullColor,
emptyColor: emptyColor
}));
}
return /*#__PURE__*/React.createElement("div", {
style: {
display: "inline-flex",
alignItems: "center"
}
}, stars);
};
export default Rating;