Created
July 2, 2015 20:53
-
-
Save bpugh/d7ef09fd71d904a0352d to your computer and use it in GitHub Desktop.
react inline edit component
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
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