-
-
Save creatorrr/ec4586a861d24eeea173 to your computer and use it in GitHub Desktop.
React help
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
import React from "react"; | |
import cx from "classnames"; | |
import _ from "underscore"; | |
import I from "immutable"; | |
import eq from "shallow-equals"; | |
// Get refs to prop types | |
const | |
{ | |
string, | |
func, | |
oneOf | |
} = React.PropTypes; | |
class Field extends React.Component { | |
constructor (props) { | |
super(props); | |
let | |
data = new Field.State({ | |
value: props.initialValue | |
}); | |
this.state = { | |
data | |
}; | |
} | |
// State template | |
static get State () { | |
return I.Record({ | |
value: null | |
}); | |
} | |
shouldComponentUpdate (nextProps, nextState) { | |
return !( | |
I.is(nextState.data, this.state.data) && | |
eq(nextProps, this.props) | |
); | |
} | |
render () { | |
let | |
{name, label, type, help, onUpdate} = this.props, | |
{data} = this.state, | |
value = data.get('value'), | |
helpClass = cx({ | |
help: true | |
}); | |
return ( | |
<div> | |
<label htmlFor={ name }> { label } </label> | |
<input | |
type={ type } | |
name={ name } | |
value={ value } | |
onBlur={ onUpdate } | |
onChange={ this.handleChange } | |
/> | |
<p className={ helpClass }> { help } </p> | |
</div> | |
); | |
} | |
handleChange (event) { | |
let | |
{value} = event.target, | |
data = new Field.State({ | |
value | |
}); | |
this.setState({ data }); | |
} | |
} | |
Field.propTypes = { | |
type: oneOf(["text", "email"]), | |
name: string.isRequired, | |
initialValue: string, | |
label: string, | |
onUpdate: func, | |
help: string | |
}; | |
Field.defaultProps = { | |
type: "text", | |
initialValue: "", | |
label: "", | |
help: "" | |
}; | |
export { Field }; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment