UNPKG

@chepchik/react-rating

Version:

React Rating is a react rating component which supports custom symbols both with inline styles and icon.

57 lines (56 loc) 2.1 kB
import React from "react"; // Helper function to determine the corresponding React node for an icon. const getIconNode = (icon) => { // If it is already a React Element just return it. if (React.isValidElement(icon)) { return icon; } // If it is an object, try to use it as a CSS style object. if (typeof icon === "object" && icon !== null) { return React.createElement("span", { style: icon }); } // If it is a string, use it as class names. if (typeof icon === "string") { return React.createElement("span", { className: icon }); } return null; }; const RatingSymbol = ({ index, inactiveIcon, activeIcon, percent, direction, readonly = false, onClick, onMouseMove, onTouchEnd, }) => { const backgroundNode = getIconNode(inactiveIcon); const showbgIcon = percent < 100; const bgIconContainerStyle = showbgIcon ? {} : { visibility: "hidden" }; const iconNode = getIconNode(activeIcon); const iconContainerStyle = { display: "inline-block", position: "absolute", overflow: "hidden", top: 0, [direction === "rtl" ? "right" : "left"]: 0, width: `${percent}%`, }; const containerStyle = { cursor: !readonly ? "pointer" : "inherit", display: "inline-block", position: "relative", }; const handleMouseMove = (e) => { if (onMouseMove) { onMouseMove(index, e); } }; const handleMouseClick = (e) => { if (onClick) { e.preventDefault(); onClick(index, e); } }; const handleTouchEnd = (e) => { if (onTouchEnd) { onTouchEnd(index, e); } }; return (React.createElement("span", { style: containerStyle, onClick: handleMouseClick, onMouseMove: handleMouseMove, onTouchMove: handleMouseMove, onTouchEnd: handleTouchEnd }, React.createElement("span", { style: bgIconContainerStyle }, backgroundNode), React.createElement("span", { style: iconContainerStyle }, iconNode))); }; export default RatingSymbol;