React input component in Coffeescript
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
TextInput = React.createClass | |
propTypes: | |
className: React.PropTypes.string, | |
id: React.PropTypes.string, | |
placeholder: React.PropTypes.string, | |
onSave: React.PropTypes.func.isRequired, | |
value: React.PropTypes.string | |
getInitialState: -> | |
value: @props.value or '' | |
render: -> | |
React.DOM.input | |
className: @props.className | |
id: @props.id | |
placeholder: @props.placeholder | |
onBlur: @_save | |
onChange: @_onChange | |
onKeyDown: @_onKeyDown | |
value: @state.value | |
_save: -> | |
@setState value: @props.onSave(@state.value) or @state.value | |
_onChange: (event) -> | |
@setState value: event.target.value | |
_onKeyDown: (event) -> | |
@_save() if event.keyCode is 13 # enter key |
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
ValidatedInput = React.createClass | |
mixins: [TextInput] #brings in the | |
propTypes: | |
process: React.PropTypes.func, | |
validate: React.PropTypes.func, | |
onValidated: React.PropTypes.func, | |
onRejected: React.PropTypes.func | |
getInitialState: -> | |
value: @props.value or '' | |
lastValue: @props.value or '' | |
process: @props.process or ((value) -> value?) | |
validate: @props.validate or (-> true) | |
render: -> | |
TextInput | |
id: @props.id | |
placeholder: @props.placeholder | |
onSave: @_save | |
value: @state.value | |
className: @props.className | |
_save: (value) -> | |
processedValue = @state.process(value) | |
if @state.validate(processedValue) | |
@props.onValidated(processedValue) if @props.onValidated? | |
@setState lastValue: @state.value | |
@props.onSave(processedValue) | |
else | |
@props.onRejected(processedValue) if @props.onRejected? | |
@state.lastValue |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment