Created
March 30, 2015 17:05
-
-
Save bichotll/01589fa5f141dfde3649 to your computer and use it in GitHub Desktop.
Rater react component
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
'use strict'; | |
var React = require('react'); | |
var Star = React.createClass({ | |
getDefaultProps: function () { | |
return { | |
isActive: false, | |
nStar: 0 | |
} | |
}, | |
handleMouseOver: function(e){ | |
this.props.onStarMouseOver(this.props.nStar); | |
}, | |
handleClick: function(){ | |
this.props.onStarClick(this.props.nStar); | |
}, | |
render: function () { | |
var className = 'glyphicon glyphicon-star star ' + this.props.nStar + ' '; | |
className += this.props.isActive? 'active': ''; | |
return ( | |
<i className={className} onMouseOver={this.handleMouseOver} onClick={this.handleClick}></i> | |
); | |
} | |
}); | |
var Rater = React.createClass({ | |
getInitialState: function() { | |
return { | |
rating: this.props.rating, | |
mouseRating: 0, | |
mouseOver: false | |
} | |
}, | |
getDefaultProps: function() { | |
return { | |
total: 5, | |
rating: 0 | |
} | |
}, | |
prepareComponentState: function(props){ | |
var usedProps = props || this.props; | |
this.setState({ | |
rating: usedProps.rating | |
}); | |
}, | |
componentWillMount: function () { | |
this.prepareComponentState(); | |
}, | |
componentWillReceiveProps: function(nextProps){ | |
this.prepareComponentState(nextProps); | |
}, | |
handleMouseLeave: function(){ | |
this.setState({ | |
mouseOver: false | |
}); | |
}, | |
handleStarMouseOver: function(nStar){ | |
this.setState({ | |
mouseOver: true, | |
mouseRating: nStar | |
}); | |
}, | |
handleStarClick: function(nStar){ | |
this.setState({ | |
rating: nStar | |
}); | |
this.props.onRateChange(nStar); | |
}, | |
render: function () { | |
var total = +this.props.total; | |
var nodes; | |
nodes = Array(total).join(',').split(',').map(function (_, i) { | |
var nStar = i+1; | |
var isActive; | |
if (this.state.mouseOver === true){ | |
isActive = nStar <= +this.state.mouseRating; | |
} else { | |
isActive = nStar <= +this.state.rating; | |
} | |
return ( | |
<Star | |
onStarClick={this.handleStarClick} | |
onStarMouseOver={this.handleStarMouseOver} | |
nStar={nStar} | |
isActive={isActive} /> | |
) | |
}.bind(this)); | |
return ( | |
<div onMouseLeave={this.handleMouseLeave} >{nodes}</div> | |
) | |
} | |
}); | |
module.exports = Rater; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment