Created
November 19, 2015 15:16
-
-
Save Spaider/43d28892352c3f306cc5 to your computer and use it in GitHub Desktop.
Event time picker component (12 hours format only; 15 minutes granularity)
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
var React = require('react'), | |
Select = require('../../Shared/Form/Select.jsx'), | |
_ = require('lodash'); | |
var TimePicker = React.createClass({ | |
propTypes: { | |
hh: React.PropTypes.number.isRequired, | |
mm: React.PropTypes.number.isRequired, | |
onChange: React.PropTypes.func | |
}, | |
fireOnChange: function(){ | |
if (this.props.onChange){ | |
this.props.onChange(this.state); | |
} | |
}, | |
handleHourSelect: function(e){ | |
this.setState( | |
{ hh: parseInt(e.target.value) }, | |
this.fireOnChange); | |
}, | |
handleMinSelect: function(e){ | |
this.setState( | |
{ mm: parseInt(e.target.value) }, | |
this.fireOnChange); | |
}, | |
handleAmPmSelect: function(e){ | |
this.setState( | |
{ ampm: e.target.value }, | |
this.fireOnChange); | |
}, | |
getInitialState: function(){ | |
var props = this.props; | |
var mm = _.round((props.mm % 60) / 15) * 15; | |
var hh = props.hh; | |
if (mm === 60){ | |
mm = 0; | |
hh += 1; | |
} | |
hh = hh % 24; | |
return { | |
hh: hh > 12 ? hh - 12 : hh, | |
mm: mm, | |
ampm: hh < 12 ? 'am' : 'pm' | |
} | |
}, | |
render: function(){ | |
var hh = this.state.hh; | |
var mm = this.state.mm; | |
var ampm = this.state.ampm; | |
return ( | |
<span> | |
<Select name='time-picker-hh' value={hh} onChange={this.handleHourSelect}> | |
{this.buildHours()} | |
</Select> | |
: | |
<Select name='time-picker-mm' value={mm} onChange={this.handleMinSelect}> | |
{this.buildMinutes()} | |
</Select> | |
<Select name='time-picker-ampm' value={ampm} onChange={this.handleAmPmSelect}> | |
<option value='am'>AM</option> | |
<option value='pm'>PM</option> | |
</Select> | |
</span> | |
); | |
}, | |
buildHours: function(){ | |
var options = []; | |
for(i = 1; i <= 12; i++){ | |
options.push(<option value={i} key={i}>{i}</option>); | |
} | |
return options; | |
}, | |
buildMinutes: function(){ | |
return _.map([0, 15, 30, 45], function(m){ | |
var text = _.padLeft(m, 2, '0'); | |
return <option value={m} key={m}>{text}</option> | |
}) | |
}, | |
}); | |
module.exports = TimePicker; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment