Created
February 10, 2015 22:41
-
-
Save bultas/6224ff31bfbcda43df05 to your computer and use it in GitHub Desktop.
ContentEditable React Component
This file contains hidden or 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
var React = require('react'); | |
var Medium = require("medium.js"); | |
function setupEditable(self) { | |
var editable = self.props.editable; | |
var extraOptions = self.props.extraOptions; | |
if (editable) { | |
var DOM = self.getDOMNode(); | |
self.medium = new Medium( | |
Object.assign({}, | |
extraOptions, {element: DOM} | |
) | |
); | |
} else if (self.medium) { | |
self.medium.destroy(); | |
} | |
} | |
var ContentEditable = React.createClass({ | |
// TODO - add isRequired to required props | |
propTypes: { | |
html: React.PropTypes.string, | |
extraOptions: React.PropTypes.object, | |
tagName: React.PropTypes.string, | |
className: React.PropTypes.string, | |
placeholder: React.PropTypes.string, | |
onChange: React.PropTypes.func, | |
editable: React.PropTypes.bool | |
}, | |
render: function() { | |
var html = this.props.html; | |
var tagName = this.props.tagName; | |
var placeholder = this.props.placeholder; | |
var className = this.props.className; | |
return ( | |
React.DOM[tagName]({ | |
className: className, | |
onInput: this._change, | |
onBlur: this._change, | |
"data-placeholder": placeholder, | |
dangerouslySetInnerHTML: { __html: html} | |
}) | |
); | |
}, | |
componentDidMount: function() { | |
setupEditable(this); | |
}, | |
componentDidUpdate: function() { | |
setupEditable(this); | |
}, | |
shouldComponentUpdate: function(nextProps){ | |
var DifferentHTML = nextProps.html !== this.getDOMNode().innerHTML; | |
var DifferentEditableState = nextProps.editable !== this.props.editable; | |
return (DifferentHTML || DifferentEditableState); | |
}, | |
_change: function(e) { | |
var contentHTML = this.getDOMNode().innerHTML; | |
this.props.onChange(contentHTML); | |
} | |
}); | |
module.exports = ContentEditable; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment