2.0 KiB
2.0 KiB
title, tags, cover, firstSeen, lastUpdated
| title | tags | cover | firstSeen | lastUpdated |
|---|---|---|---|---|
| Star rating | components,children,input,state | lake-church | 2018-10-18T14:33:45+03:00 | 2021-10-13T19:29:39+02:00 |
Renders a star rating component.
- Define a
Starcomponent. It renders each individual star with the appropriate appearance, based on the parent component's state. - Define a
StarRatingcomponent. Use theuseState()hook to define theratingandselectionstate variables with the appropriate initial values. - Create a method,
hoverOver, that updatesselectedaccording to the providedevent, using the .data-star-idattribute of the event's target or resets it to0if called with anullargument. - Use
Array.from()to create an array of5elements andArray.prototype.map()to create individual<Star>components. - Handle the
onMouseOverandonMouseLeaveevents of the wrapping element usinghoverOver. Handle theonClickevent usingsetRating.
.star {
color: #ff9933;
cursor: pointer;
}
const Star = ({ marked, starId }) => {
return (
<span data-star-id={starId} className="star" role="button">
{marked ? '\u2605' : '\u2606'}
</span>
);
};
const StarRating = ({ value }) => {
const [rating, setRating] = React.useState(parseInt(value) || 0);
const [selection, setSelection] = React.useState(0);
const hoverOver = event => {
let val = 0;
if (event && event.target && event.target.getAttribute('data-star-id'))
val = event.target.getAttribute('data-star-id');
setSelection(val);
};
return (
<div
onMouseOut={() => hoverOver(null)}
onClick={e => setRating(e.target.getAttribute('data-star-id') || rating)}
onMouseOver={hoverOver}
>
{Array.from({ length: 5 }, (v, i) => (
<Star
starId={i + 1}
key={`star_${i + 1}`}
marked={selection ? selection >= i + 1 : rating >= i + 1}
/>
))}
</div>
);
};
ReactDOM.render(<StarRating value={2} />, document.getElementById('root'));