38 - Rating System with Stars or Thumbs Up/Down

Description

Develop a React component enabling users to express ratings using either stars or thumbs up/down.

  • Displays either star icons or thumbs up/down icons for rating selection.

  • Visually indicates the selected rating level.

  • Stores the selected rating value for later use.

  • Optionally supports partial ratings (half-stars).

  • Optionally allows users to clear their rating.

Algorithm

  1. Component Structure:

    • Define a functional component named RatingSystem.

    • Accept props for:

      • ratingType: String indicating the type of rating system ("stars" or "thumbs").

      • initialRating: Initial rating value (optional).

      • maxRating: Maximum allowable rating value (optional).

      • allowHalfRatings: Boolean indicating if half-ratings are allowed (optional).

      • onRatingChanged: Function to handle rating changes.

    • Maintain internal state for:

      • selectedRating: Current selected rating value.

  2. Rating Display and Handling:

    • Render appropriate icons based on ratingType.

    • Attach event listeners (click or hover, depending on preference) to individual icons:

      • Update selectedRating state based on user interaction, considering max rating value.

      • Call onRatingChanged prop function with the new rating value.

  3. Partial Ratings (optional):

    • If allowHalfRatings:

      • Employ CSS styling or JavaScript logic to handle half-star or partial thumb states based on the selected rating.

  4. Clearing Rating (optional):

    • Provide a mechanism (e.g., "clear" button or icon) to reset the rating to zero and update the selectedRating state.

  5. Visual Representation:

    • Use visually distinct styles for unselected, selected, and (if applicable) half-selected icons.

    • Consider hover effects or other interactive cues to guide user interaction.

Code

import React, { useState } from 'react';

const RatingIcon = ({ icon, isSelected, onClick }) => (
  <span onClick={onClick} className={`rating-icon ${isSelected ? 'selected' : ''}`}>
    {icon}
  </span>
);

const RatingSystem = ({
  ratingType,
  initialRating = 0,
  maxRating = 5,
  allowHalfRatings = false,
  onRatingChanged,
}) => {
  const [selectedRating, setSelectedRating] = useState(initialRating);

  const handleIconClick = (rating) => {
    if (rating <= maxRating) {
      setSelectedRating(allowHalfRatings ? rating / 2 : Math.floor(rating));
      if (onRatingChanged) onRatingChanged(selectedRating);
    }
  };

  const renderRatingIcons = () => {
    const icons = [];
    for (let i = 1; i <= maxRating; i++) {
      const fullIcon = ratingType === 'stars' ? '★' : '';
      const halfIcon = ratingType === 'stars' ? '½' : '';
      const isSelected = i <= selectedRating;
      const isHalfSelected = allowHalfRatings && i * 2 === Math.ceil(selectedRating * 2);

      icons.push(
        <RatingIcon
          key={i}
          icon={isSelected ? fullIcon : isHalfSelected ? halfIcon : ''}
          isSelected={isSelected || isHalfSelected}
          onClick={() => handleIconClick(i)}
        />
      );
    }
    return icons;
  };

  const clearRating = () => {
    setSelectedRating(0);
    if (onRatingChanged) onRatingChanged(0);
  };

  // Optionally render a clear button if desired
  // ...

  return (
    <div className="rating-system">
      {renderRatingIcons()}
      {/* Optionally render clear button here */}
    </div>
  );
};

export default RatingSystem;

Explanation

  • RatingIcon component: Renders individual star or thumbs up/down icons with selected/unselected states.

  • RatingSystem component:

    • Manages selected rating state and handles prop options (type, initial rating, max rating, etc.).

    • Renders RatingIcon components dynamically based on chosen rating type and max rating.

    • Handles icon click events, updating selected rating and calling the onRatingChanged prop function.

    • Optionally provides a method to clear the rating and reset state.

    • You can further customize the visual aspects of the rating system through CSS styling.

Additional Notes

  • This example demonstrates a basic implementation. You can extend it to include features like hover effects, animations, custom icons, and different rating scales.

  • Consider user experience aspects like hover hints or visual cues to indicate allowed rating selections.

Last updated