Skip to content

Instantly share code, notes, and snippets.

@name-k
Forked from andrewgleave/ContentEditableLabel.js
Last active August 29, 2015 14:26
Show Gist options
  • Save name-k/18c429ce31249473d70c to your computer and use it in GitHub Desktop.
Save name-k/18c429ce31249473d70c to your computer and use it in GitHub Desktop.
An editable React.js label element based on the contenteditable attribute
/** @jsx React.DOM */
'use strict';
var React = require('react');
var ContentEditableLabel = React.createClass({
propTypes: {
tag: React.PropTypes.func,
className: React.PropTypes.string,
onChange: React.PropTypes.func,
onComplete: React.PropTypes.func,
initialText: React.PropTypes.string,
autofocus: React.PropTypes.bool
},
getDefaultProps: function() {
return {
autofocus: true,
tag: React.DOM.span
};
},
componentDidMount:function() {
if(this.props.autofocus) {
this.clearAndFocus();
}
this.cancelled = false;
},
shouldComponentUpdate: function(nextProps){
return nextProps.initialText !== this.getText();
},
clearAndFocus: function() {
var elem = this.refs.element.getDOMNode();
elem.focus();
elem.textContent = '';
},
getText: function() {
if(this.cancelled) return '';
return this.refs.element.getDOMNode().textContent;
},
handleClick: function() {
if(!this.props.autofocus) {
this.clearAndFocus();
}
},
handleChange: function(){
var text = this.getText();
if(this.props.onChange && text !== this.previousText) {
this.props.onChange(text);
}
this.previousText = text;
},
handleKeyUp: function(e) {
if(e.which === 13 || e.which === 27) {
this.cancelled = (e.which === 27);
this.refs.element.getDOMNode().blur();
}
},
handleBlur: function() {
this.props.onComplete(this.getText());
this.cancelled = false;
},
render: function(){
return (this.props.tag({
ref: 'element',
className: this.props.className,
onClick: this.handleClick,
onInput: this.handleChange,
onKeyUp: this.handleKeyUp,
onBlur: this.handleBlur,
contentEditable: 'true'
}, this.props.initialText));
}
});
module.exports = ContentEditableLabel;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment