Last active
September 15, 2016 09:32
-
-
Save andrewgleave/11231384 to your computer and use it in GitHub Desktop.
An editable React.js label element based on the contenteditable attribute
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
/** @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
hi..How do you use it ? can you give an example?