Skip to content
The Chat Archive
o1-mini-2024-09-12· OpenAI WildChat-4.8M (AI2)

import React, { useState } from 'react'; interface RatingProps { maxStars: number;…

  1. User

    import React, { useState } from 'react';

    interface RatingProps { maxStars: number; initialRating?: number; onChange?: (rating: number) => void; // Добавим возможность передавать класс для контейнера className?: string; }

    const Rating: React.FC = ({ maxStars, initialRating = 0, onChange, className, }) => { const [selectedStars, setSelectedStars] = useState(initialRating); const [hoveredStars, setHoveredStars] = useState(0);

    const handleStarClick = (rating: number) => { setSelectedStars(rating); if (onChange) { onChange(rating); } };

    const handleMouseEnter = (rating: number) => { setHoveredStars(rating); };

    const handleMouseLeave = () => { setHoveredStars(0); };

    const stars = [];

    for (let i = 1; i <= maxStars; i++) { stars.push( <span key={i} style={{ color: '#FFD700', fontSize: '1.5rem', cursor: 'pointer' }} onClick={() => handleStarClick(i)} onMouseEnter={() => handleMouseEnter(i)} onMouseLeave={handleMouseLeave} > {i <= (hoveredStars || selectedStars) ? '★' : '☆'} ); }

    return {stars}; };

    export default Rating; улучшить

  2. Assistant

    Certainly! Enhancing your Rating component can make it more robust, accessible, and flexible. Below are several improvements:

    1. Accessibility Enhancements:

      • Keyboard Navigation: Allow users to navigate and select ratings using the keyboard.
      • ARIA Attributes: Provide meaningful ARIA labels for screen readers.
    2. Customization:

      • Custom Icons: Allow passing custom icons instead of relying on Unicode stars.
      • Style Flexibility: Use CSS classes more effectively to enable easier styling.
    3. Controlled vs. Uncontrolled:

      • Controlled Component Support: Allow the parent component to control the rating value.
    4. Performance Optimizations:

      • Memoization: Use React.memo to prevent unnecessary re-renders.
      • Use Callback Hooks: Optimize event handlers with useCallback.
    5. TypeScript Enhancements:

      • Strict Typing: Improve type definitions for better type safety.
    6. Additional Features:

      • Half-Star Ratings: Support for half-star increments.
      • Read-Only Mode: Option to display the rating without allowing changes.

    Below is the enhanced Rating component incorporating these improvements:

    import React, { useState, useCallback, KeyboardEvent } from 'react';
    
    interface RatingProps {
      maxStars: number;
      initialRating?: number;
      onChange?: (rating: number) => void;
      className?: string;
      // New props for customization
      readOnly?: boolean;
      allowHalf?: boolean;
      starIconFilled?: React.ReactNode;
      starIconEmpty?: React.ReactNode;
      // ARIA label
      ariaLabel?: string;
    }
    
    const Rating: React.FC<RatingProps> = React.memo(
      ({
        maxStars,
        initialRating = 0,
        onChange,
        className = '',
        readOnly = false,
        allowHalf = false,
        starIconFilled = '★',
        starIconEmpty = '☆',
        ariaLabel = 'Rating',
      }) => {
        const [selectedStars, setSelectedStars] = useState<number>(initialRating);
        const [hoveredStars, setHoveredStars] = useState<number>(0);
    
        const handleStarClick = useCallback(
          (rating: number) => {
            if (readOnly) return;
            setSelectedStars(rating);
            if (onChange) {
              onChange(rating);
            }
          },
          [onChange, readOnly]
        );
    
        const handleMouseEnter = useCallback(
          (rating: number) => {
            if (readOnly) return;
            setHoveredStars(rating);
          },
          [readOnly]
        );
    
        const handleMouseLeave = useCallback(() => {
          if (readOnly) return;
          setHoveredStars(0);
        }, [readOnly]);
    
        const handleKeyDown = useCallback(
          (event: KeyboardEvent<HTMLSpanElement>, index: number) => {
            if (readOnly) return;
            if (event.key === 'Enter' || event.key === ' ') {
              event.preventDefault();
              handleStarClick(index);
            }
            if (event.key === 'ArrowRight' && index < maxStars) {
              event.preventDefault();
              handleStarClick(index + 1);
            }
            if (event.key === 'ArrowLeft' && index > 1) {
              event.preventDefault();
              handleStarClick(index - 1);
            }
          },
          [handleStarClick, maxStars, readOnly]
        );
    
        const renderStar = (i: number) => {
          const isFilled = hoveredStars
            ? i <= hoveredStars
            : i <= selectedStars;
    
          return (
            <span
              key={i}
              role="radio"
              aria-checked={i === selectedStars}
              tabIndex={readOnly ? -1 : 0}
              className={`rating-star ${isFilled ? 'filled' : 'empty'}`}
              style={{
                color: '#FFD700',
                fontSize: '1.5rem',
                cursor: readOnly ? 'default' : 'pointer',
                transition: 'color 200ms',
                marginRight: '4px',
              }}
              onClick={() => handleStarClick(i)}
              onMouseEnter={() => handleMouseEnter(i)}
              onMouseLeave={handleMouseLeave}
              onKeyDown={(e) => handleKeyDown(e, i)}
              aria-label={`${i} Star${i > 1 ? 's' : ''}`}
            >
              {isFilled ? starIconFilled : starIconEmpty}
            </span>
          );
        };
    
        return (
          <div
            className={`rating-container ${className}`}
            role="radiogroup"
            aria-label={ariaLabel}
          >
            {Array.from({ length: maxStars }, (_, i) => renderStar(i + 1))}
          </div>
        );
      }
    );
    
    export default Rating;
    

    Explanation of Improvements

    1. Accessibility:

      • Role Attributes: Added role="radiogroup" to the container and role="radio" to each star for better semantics.
      • ARIA Labels: Each star has an aria-label describing its value.
      • Keyboard Navigation: Users can navigate using arrow keys and select with Enter or Space.
    2. Customization:

      • Custom Icons: Props starIconFilled and starIconEmpty allow passing custom icons (e.g., SVGs or images).
      • Read-Only Mode: The readOnly prop disables interactions, making the component display-only.
    3. Controlled vs. Uncontrolled:

      • While the component primarily uses internal state, it can be extended to accept a rating prop to become fully controlled if needed.
    4. Performance Optimizations:

      • React.memo: Prevents unnecessary re-renders when props haven't changed.
      • useCallback: Memoizes event handlers to avoid recreating functions on each render.
    5. TypeScript Enhancements:

      • Strict Typing: Ensures all props have appropriate types, enhancing type safety.
    6. Additional Features:

      • Half-Star Support: (Note: Implementing half-stars would require additional logic. This example includes an allowHalf prop placeholder for future extension.)
      • Style Flexibility: Added rating-star and rating-container classes for easier CSS targeting.

    Usage Example

    Here's how you can use the enhanced Rating component:

    import React, { useState } from 'react';
    import Rating from './Rating'; // Adjust the import path accordingly
    
    const App: React.FC = () => {
      const [rating, setRating] = useState<number>(3);
    
      const handleRatingChange = (newRating: number) => {
        setRating(newRating);
        console.log(`Rated: ${newRating}`);
      };
    
      return (
        <div>
          <h1>Rate our service:</h1>
          <Rating
            maxStars={5}
            initialRating={rating}
            onChange={handleRatingChange}
            className="custom-rating"
            ariaLabel="Service Rating"
          />
        </div>
      );
    };
    
    export default App;
    

    CSS Styling

    To style the component, you can add CSS targeting the provided classes:

    .rating-container {
      display: flex;
      align-items: center;
    }
    
    .rating-star {
      transition: color 200ms;
    }
    
    .rating-star.filled {
      color: #FFD700;
    }
    
    .rating-star.empty {
      color: #CCCCCC;
    }
    
    .rating-star:focus {
      outline: 2px solid #000;
    }
    

    Further Enhancements

    1. Half-Star Functionality:

      • Implement logic to handle half-star ratings, possibly by detecting click positions within a star.
    2. Controlled Component Support:

      • Accept a rating prop and synchronize it with internal state, allowing the parent to control the rating.
    3. Animations:

      • Add subtle animations on hover or selection to enhance user experience.
    4. Testing:

      • Write unit and integration tests to ensure all functionalities work as expected.

    By incorporating these improvements, your Rating component will be more versatile, user-friendly, and maintainable.