Skip to content

Instantly share code, notes, and snippets.

@whalesalad
Last active April 5, 2016 22:09
Show Gist options
  • Select an option

  • Save whalesalad/fb01e37c86f60b44cbc2ae41e6ed526f to your computer and use it in GitHub Desktop.

Select an option

Save whalesalad/fb01e37c86f60b44cbc2ae41e6ed526f to your computer and use it in GitHub Desktop.
class EditableFieldNameComponent extends React.Component {
constructor(props) {
super(props);
this.model.on(`change:${this.attribute}`, function(x, value, y) {
this.setState({text: value});
}.bind(this));
this.state = {
editing: this.props.editing || false,
text: this.model.get(this.attribute)
}
}
get model() {
return this.props.model;
}
get attribute() {
return this.props.attribute;
}
set text(text) {
this.model.set(this.attribute, text);
}
get text() {
return this.state.text || 'Unnamed Field'
}
startEdit() {
this.setState({editing: true}, () => {
this.refs.nameInput.focus();
});
}
stopEditing() {
this.setState({editing: false});
}
handleKeyUp(e) {
if (e.keyCode === ENTER_KEY) {
this.text = e.target.value;
this.stopEditing();
} else if (e.keyCode === ESC_KEY) {
this.stopEditing();
}
}
handleBlur(e) {
this.text = e.target.value;
this.stopEditing();
}
render() {
if (this.state.editing) {
return (<div className="field-name-inline-editor">
<input ref="nameInput"
type="text"
defaultValue={this.state.text}
onKeyUp={this.handleKeyUp.bind(this)}
onBlur={this.handleBlur.bind(this)} />
</div>)
} else {
return (
<p className="field-name" onClick={this.startEdit.bind(this)}>
{this.text}
<span className="help-text">Click to edit</span>
</p>
);
}
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment