Skip to content

Instantly share code, notes, and snippets.

@creatorrr
Last active August 29, 2015 14:16
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save creatorrr/ec4586a861d24eeea173 to your computer and use it in GitHub Desktop.
Save creatorrr/ec4586a861d24eeea173 to your computer and use it in GitHub Desktop.
React help
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