Skip to content

Instantly share code, notes, and snippets.

@bpugh
Created July 2, 2015 20:53
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 bpugh/d7ef09fd71d904a0352d to your computer and use it in GitHub Desktop.
Save bpugh/d7ef09fd71d904a0352d to your computer and use it in GitHub Desktop.
react inline edit component
var React = require('react');
var EditableText = React.createClass({
propTypes: {
onSubmit: React.PropTypes.func.isRequired
,validator: React.PropTypes.func
,enableEditing: React.PropTypes.bool
,value: React.PropTypes.oneOfType([
React.PropTypes.string,
React.PropTypes.number,
])
},
getInitialState: function() {
return {
editing: false
,invalid: false
,newValue: this.props.value
};
},
getDefaultProps: function() {
return {
enableEditing: true
};
},
edit() {
this.setState({editing: true});
},
handleChange(e){
this.setState({newValue: e.target.value});
},
cancelEdit() {
this.setState({
editing: false
,invalid: false
});
},
submit(e) {
e.preventDefault();
if(!this.props.validator || this.props.validator(this.state.newValue)){
this.props.onSubmit(this.state.newValue);
this.cancelEdit();
}
else{
this.setState({invalid: true});
}
},
render: function() {
var inputForm = (
<form onSubmit={this.submit}
className={this.state.invalid ? "has-error" : ""} >
<input type="text" autoFocus
onChange={this.handleChange}
onBlur={this.cancelEdit}
className="form-control average" />
</form>
);
if(this.props.enableEditing){
return (
<div className="inline-edit">
{this.state.editing ?
{inputForm} :
<a onClick={this.edit} title="Edit" className={'average'}>{this.props.value || 'Add'}</a>
}
</div>
);
}
else {
return (<span>{this.props.value}</span>);
}
}
});
module.exports = EditableText;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment