Skip to content

Instantly share code, notes, and snippets.

@ericgeorgeriley
Created October 29, 2019 12:33
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save ericgeorgeriley/90e958dff23f6cbca9bec83cab8faae9 to your computer and use it in GitHub Desktop.
a really simple component for star rating input
import React from 'react';
export class StarRating extends React.Component {
constructor(props) {
super(props);
this.state = {
stars: [],
rating: 0,
hovered: 0,
selectedIcon: "★",
deselectedIcon: "☆"
};
let outOf = props.outOf ? props.outOf : 5;
for (var i = 0; i < outOf; i++) {
this.state.stars.push(i + 1);
}
}
changeRating(newRating) {
this.setState({
rating: newRating
});
if (this.props.onChange)
this.props.onChange(newRating);
}
hoverRating(rating) {
this.setState({
hovered: rating
});
}
render() {
const { stars, rating, hovered, deselectedIcon, selectedIcon } = this.state;
return (
<div>
<div className="rating" style={{ fontSize: '5em', color: "#38d39f" }}>
{stars.map(star => {
return (
<span
style={{ cursor: 'pointer' }}
onClick={() => { this.changeRating(star); }}
onMouseEnter={() => { this.hoverRating(star); }}
onMouseLeave={() => { this.hoverRating(0); }}
>
{rating < star ?
hovered < star ? deselectedIcon : selectedIcon
:
selectedIcon
}
</span>
);
})}
</div>
</div>
);
}
}
export default (StarRating);
@ericgeorgeriley
Copy link
Author

rendered_start_rating
This is how the rendered component appears

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment