Skip to content

Instantly share code, notes, and snippets.

@thecaddy
Created February 23, 2016 15:25
Show Gist options
  • Select an option

  • Save thecaddy/61a63d92683ed1ebfb05 to your computer and use it in GitHub Desktop.

Select an option

Save thecaddy/61a63d92683ed1ebfb05 to your computer and use it in GitHub Desktop.

Revisions

  1. Joel Trost renamed this gist Feb 23, 2016. 1 changed file with 0 additions and 0 deletions.
    File renamed without changes.
  2. Joel Trost created this gist Feb 23, 2016.
    66 changes: 66 additions & 0 deletions gistfile1.txt
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,66 @@
    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);
    }
    }