Skip to content

Instantly share code, notes, and snippets.

@paulkaplan
Last active August 29, 2015 14:05
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save paulkaplan/968500aad6bb1c400928 to your computer and use it in GitHub Desktop.
React input component in Coffeescript
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
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