Skip to content

Instantly share code, notes, and snippets.

@andrewgleave
Last active September 15, 2016 09:32
Show Gist options
  • Star 13 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save andrewgleave/11231384 to your computer and use it in GitHub Desktop.
Save andrewgleave/11231384 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;
@fddayan
Copy link

fddayan commented Feb 26, 2015

hi..How do you use it ? can you give an example?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment