Conner Frey
Conner Frey

Reputation: 563

Interrupt Enter Key On ContentEditable Div In ReactJS

I want to interrupt the Enter key and stop it from injecting the html code into the ContentEditable div. My current code does not work because it does not interrupt the Enter key. However, if I type, press enter, then type again, it deletes the inner html elements. But still, this is not what I want. I want the elements to NOT go into the ContentEditable div to begin with when I press enter rather than having to strip them out.

I am essentially using this as an "input that scales with its content". If there is a better way to do this, please let me know!

import ReactDOM from 'react-dom'

export default class MyInput extends React.Component {    
  componentWillReceiveProps(nextProps) {
    this.setState({value: nextProps.html});
  }

  shouldComponentUpdate(nextProps){
    return nextProps.html !== ReactDOM.findDOMNode(this).innerHTML;
  }

  componentDidUpdate() {
    if ( this.htmlEl && this.props.html !== this.htmlEl.innerHTML ) {
     this.htmlEl.innerHTML = this.props.html;
    }
  }

  emitChange(){
    var html = ReactDOM.findDOMNode(this).innerHTML;

    // regex to remove tags created after pressing enter
    value = value.replace(/<div>/g, '');
    value = value.replace(/<\/div>/g, '');
    value = value.replace(/<br>/g, '');

    if (this.props.onChange && html !== this.lastHtml) {
      this.props.onChange(html);
    }
    this.lastHtml = html;
    this.forceUpdate();
  }

  render() {
    var html = this.state.value;
    return (
      <div
        dangerouslySetInnerHTML={{__html: html}}
        onInput={this.emitChange.bind(this)}
        onBlur={this.emitChange.bind(this)}
        contentEditable
      ></div>
    )
  }
};<kbd>

Upvotes: 5

Views: 5502

Answers (2)

Conner Frey
Conner Frey

Reputation: 563

  //  function handler inside class declaration
  keyPress(event) {
    if(event.charCode == 13) {
      event.preventDefault()
    }
  }

  //  in render function
  <div
    dangerouslySetInnerHTML={{__html: html}}
    onInput={this.emitChange.bind(this)}
    onBlur={this.emitChange.bind(this)}
    onKeyPress={this.keyPress.bind(this)}
    contentEditable
  ></div>

Upvotes: 9

ZhiLI
ZhiLI

Reputation: 209

bind you div with a keyboard event and then:

var keyCode = event.which || event.keyCode;
keyCode === 13 && event.preventDefault();

Upvotes: 2

Related Questions