Skip to content

Instantly share code, notes, and snippets.

@thecaddy
Created February 23, 2016 15:25
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save thecaddy/61a63d92683ed1ebfb05 to your computer and use it in GitHub Desktop.
Save thecaddy/61a63d92683ed1ebfb05 to your computer and use it in GitHub Desktop.
React wrapper for medium editor
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);
}
}
@thecaddy
Copy link
Author

How to call:

<Medium
  tag="div"
  ref="descriptionEditor"
  className={'myclassname}
  onFocus={this.handleFocus}
  onBlur={this.handleBlur}
  text={this.props.description}
  contentEditable={true}
  onChange={this.handleChange}
  options={{
    disableEditing: false,
    field: 'description',
    toolbar: {
      buttons: ['bold', 'italic', 'anchor', 'quote', 'underline']
    }
  }}
/>

@owenhoskins
Copy link

owenhoskins commented May 4, 2016

For calling, should it be <MediumEditor>?

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