Skip to content

Instantly share code, notes, and snippets.

@nkt
Created June 19, 2015 13:44
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 nkt/8cfa4089d755ec10a353 to your computer and use it in GitHub Desktop.
Save nkt/8cfa4089d755ec10a353 to your computer and use it in GitHub Desktop.
const React = require('react');
const classNames = require('classnames');
const Input = React.createClass({
propTypes: {
id: React.PropTypes.string.isRequired,
className: React.PropTypes.string,
title: React.PropTypes.string,
help: React.PropTypes.string,
type: React.PropTypes.oneOf([
'text', 'password', 'number', 'email', 'url', 'search', 'tel',
'datetime', 'datetime-local', 'date', 'month', 'time', 'week',
'file', 'textarea', 'select', 'static'
]),
value: React.PropTypes.any,
defaultValue: React.PropTypes.any,
size: React.PropTypes.oneOf(['large', 'small']),
feedback: React.PropTypes.oneOfType([
React.PropTypes.bool,
React.PropTypes.string
]),
onFeedbackClick: React.PropTypes.func,
state: React.PropTypes.oneOf([null, 'success', 'warning', 'error']),
children: React.PropTypes.node
},
getInitialState() {
return {
dirty: false,
valid: true
};
},
renderLabel() {
if (this.props.title) {
return <label className="control-label" htmlFor={this.props.id}>{this.props.title}</label>;
}
return null;
},
renderHelp() {
if (this.props.help) {
return <span className="help-block">{this.props.help}</span>;
}
return null;
},
renderFeedback() {
if (!this.props.feedback) {
return null;
}
let glyph = typeof this.props.feedback === 'string' ? this.props.feedback : glyph = {
success: 'check',
warning: 'warning',
error: 'times'
}[this.props.state];
return (
<span className={`form-control-feedback fa fa-${glyph}`} onClick={this.props.onFeedbackClick} />
);
},
renderInput() {
let {type, className} = this.props;
if (type === 'static') {
return (
<p {...this.props} className={classNames(className, 'form-control-static')}>
{this.props.value}
</p>
);
}
className = classNames(className, {
'form-control': type !== 'file'
});
switch (type) {
case 'select':
return (
<select {...this.props} className={className}>
{this.props.children}
</select>
);
case 'textarea':
return <textarea {...this.props} className={className} />;
default:
return <input {...this.props} className={className} />;
}
},
render() {
const className = classNames('form-group', this.props.className, {
'form-group-lg': this.props.size === 'large',
'form-group-sm': this.props.size === 'small',
'has-feedback': this.props.feedback,
'has-success': this.props.state === 'success',
'has-warning': this.props.state === 'warning',
'has-error': this.props.state === 'error'
});
return (
<div className={className}>
{this.renderLabel()}
{this.renderInput()}
{this.renderHelp()}
{this.renderFeedback()}
</div>
);
}
});
module.exports = Input;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment