Created
October 2, 2014 18:11
-
-
Save gaearon/f8ffbfd106092580d490 to your computer and use it in GitHub Desktop.
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'), | |
escapeTextForBrowser = require('react/lib/escapeTextForBrowser'), | |
{ PropTypes } = React; | |
var UncontrolledContentEditable = React.createClass({ | |
propTypes: { | |
component: PropTypes.func, | |
onChange: PropTypes.func.isRequired, | |
text: PropTypes.string, | |
placeholder: PropTypes.string, | |
editable: PropTypes.bool | |
}, | |
getDefaultProps() { | |
return { | |
component: React.DOM.div, | |
editable: false | |
}; | |
}, | |
getInitialState() { | |
return { | |
initialText: this.props.text | |
}; | |
}, | |
componentWillReceiveProps(nextProps) { | |
if (nextProps.editable && !this.props.editable) { | |
this.setState({ | |
initialText: nextProps.text | |
}); | |
} | |
}, | |
componentWillUpdate(nextProps) { | |
if (!nextProps.editable && this.props.editable) { | |
this.getDOMNode().innerHTML = escapeTextForBrowser(this.state.initialText); | |
} | |
}, | |
render() { | |
var html = escapeTextForBrowser(this.props.editable ? | |
this.state.initialText : | |
this.props.text | |
); | |
return ( | |
<this.props.component onInput={this.handleChange} | |
onBlur={this.handleChange} | |
contentEditable={this.props.editable} | |
dangerouslySetInnerHTML={{__html: html}} /> | |
); | |
}, | |
handleChange(e) { | |
if (!e.target.textContent.trim().length) { | |
e.target.innerHTML = ''; | |
} | |
this.props.onChange(e); | |
} | |
}); | |
module.exports = UncontrolledContentEditable; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment