Created
February 23, 2016 15:25
-
-
Save thecaddy/61a63d92683ed1ebfb05 to your computer and use it in GitHub Desktop.
React wrapper for medium editor
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
import _ from 'lodash' | |
import blacklist from 'blacklist' | |
import React, {Component, PropTypes} from 'react' | |
import ReactDOM from 'react-dom' | |
let Medium; | |
if (typeof document !== 'undefined') { | |
Medium = require('medium-editor'); | |
} | |
export default class MediumEditor extends Component { | |
static propTypes = { | |
tag: PropTypes.string.isRequired, | |
text: PropTypes.string.isRequired, | |
options: PropTypes.object, | |
onChange: PropTypes.func | |
} | |
constructor(props) { | |
super(props) | |
this.state = { | |
text: this.props.text | |
} | |
} | |
componentDidMount = () => { | |
const dom = ReactDOM.findDOMNode(this); | |
this.medium = new Medium(dom, this.props.options); | |
this.medium.subscribe('editableInput', (event) => { | |
this._updated = true; | |
this.change(dom.innerHTML); | |
}); | |
} | |
componentWillReceiveProps(nextProps) { | |
if (nextProps.text !== this.state.text && !this._updated) { | |
this.setState({text: nextProps.text}); | |
} | |
if (this._updated) this._updated = false; | |
} | |
componentWillUnmount = () => { | |
this.medium.destroy(); | |
} | |
change = (text) => { | |
if (this.props.onChange && text !== '<p><br></p>') { | |
this.props.onChange(text, this.medium) | |
} | |
} | |
render() { | |
require('./Medium.scss') | |
const tag = this.props.tag; | |
const props = blacklist(this.props, 'tag', 'dangerouslySetInnerHTML'); | |
_.assign(props, { | |
contentEditable: props.hasOwnProperty('contentEditable') ? props.contentEditable : true, | |
dangerouslySetInnerHTML: {__html: this.state.text} | |
}); | |
return React.createElement(tag, props); | |
} | |
} |
For calling, should it be <MediumEditor>
?
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
How to call: