Created
March 16, 2021 15:00
-
-
Save MalloyDelacroix/a46efa6fab3c442448895c189d551a8a to your computer and use it in GitHub Desktop.
Simple React Star Rating Bar
This file contains hidden or 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
.rating { | |
cursor: default; | |
.star { | |
font-size: 1.75rem; | |
color: grey; | |
} | |
.star-selected { | |
color: darkorange; | |
} | |
.star-hovered { | |
color: orange; | |
} | |
} |
This file contains hidden or 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'; | |
import PropTypes from 'prop-types'; | |
import './star-rating.scss'; | |
class StarRating extends React.Component { | |
constructor(props) { | |
super(props); | |
this.state = { | |
rating: this.props.initialRating, | |
hoverValue: 0, | |
} | |
} | |
handleHover = e => { | |
if (! this.props.readOnly) { | |
this.setState({hoverValue: e.target.dataset.value}) | |
} | |
} | |
clearHover = () => { | |
if (! this.props.readOnly) { | |
this.setState({hoverValue: 0}) | |
} | |
} | |
handleClick = e => { | |
if (! this.props.readOnly) { | |
let value = e.target.dataset.value | |
this.setState({rating: value}) | |
this.props.onClick(value); | |
} | |
} | |
renderStar(value) { | |
let classValue = 'star'; | |
if (this.state.hoverValue >= value) { | |
classValue += ' star-hovered'; | |
} else if (this.state.rating >= value) { | |
classValue += ' star-selected'; | |
} | |
return ( | |
<span className={classValue} key={value} data-value={value} onMouseOver={this.handleHover} | |
onClick={this.handleClick}> | |
★ | |
</span> | |
) | |
} | |
render() { | |
return ( | |
<div className="rating" onMouseLeave={this.clearHover}> | |
{[...Array(this.props.starCount).keys()].map(value => { | |
return this.renderStar(value + 1); | |
})} | |
</div> | |
) | |
} | |
} | |
export default StarRating; | |
StarRating.propTypes = { | |
initialRating: PropTypes.number.isRequired, | |
starCount: PropTypes.number, | |
readOnly: PropTypes.bool, | |
onClick: PropTypes.func.isRequired, | |
} | |
StarRating.defaultProps = { | |
starCount: 10, | |
readOnly: false, | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment