import React, { useState } from 'react'; interface RatingProps { maxStars: number;…
- 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; улучшить
- Assistant
Certainly! Enhancing your
Ratingcomponent can make it more robust, accessible, and flexible. Below are several improvements:-
Accessibility Enhancements:
- Keyboard Navigation: Allow users to navigate and select ratings using the keyboard.
- ARIA Attributes: Provide meaningful ARIA labels for screen readers.
-
Customization:
- Custom Icons: Allow passing custom icons instead of relying on Unicode stars.
- Style Flexibility: Use CSS classes more effectively to enable easier styling.
-
Controlled vs. Uncontrolled:
- Controlled Component Support: Allow the parent component to control the rating value.
-
Performance Optimizations:
- Memoization: Use
React.memoto prevent unnecessary re-renders. - Use Callback Hooks: Optimize event handlers with
useCallback.
- Memoization: Use
-
TypeScript Enhancements:
- Strict Typing: Improve type definitions for better type safety.
-
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
Ratingcomponent 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
-
Accessibility:
- Role Attributes: Added
role="radiogroup"to the container androle="radio"to each star for better semantics. - ARIA Labels: Each star has an
aria-labeldescribing its value. - Keyboard Navigation: Users can navigate using arrow keys and select with
EnterorSpace.
- Role Attributes: Added
-
Customization:
- Custom Icons: Props
starIconFilledandstarIconEmptyallow passing custom icons (e.g., SVGs or images). - Read-Only Mode: The
readOnlyprop disables interactions, making the component display-only.
- Custom Icons: Props
-
Controlled vs. Uncontrolled:
- While the component primarily uses internal state, it can be extended to accept a
ratingprop to become fully controlled if needed.
- While the component primarily uses internal state, it can be extended to accept a
-
Performance Optimizations:
- React.memo: Prevents unnecessary re-renders when props haven't changed.
- useCallback: Memoizes event handlers to avoid recreating functions on each render.
-
TypeScript Enhancements:
- Strict Typing: Ensures all props have appropriate types, enhancing type safety.
-
Additional Features:
- Half-Star Support: (Note: Implementing half-stars would require additional logic. This example includes an
allowHalfprop placeholder for future extension.) - Style Flexibility: Added
rating-starandrating-containerclasses for easier CSS targeting.
- Half-Star Support: (Note: Implementing half-stars would require additional logic. This example includes an
Usage Example
Here's how you can use the enhanced
Ratingcomponent: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
-
Half-Star Functionality:
- Implement logic to handle half-star ratings, possibly by detecting click positions within a star.
-
Controlled Component Support:
- Accept a
ratingprop and synchronize it with internal state, allowing the parent to control the rating.
- Accept a
-
Animations:
- Add subtle animations on hover or selection to enhance user experience.
-
Testing:
- Write unit and integration tests to ensure all functionalities work as expected.
By incorporating these improvements, your
Ratingcomponent will be more versatile, user-friendly, and maintainable. -