a really simple component for star rating input
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This is how the rendered component appears