How to put/paste the content where cursor is there in content editable div

633 Views Asked by At

I am a newbie on react. I have a content editable div. What I want is Make a button, on button click -> "HEY" word will be added. Let's say my content length is 100, and I have clicked on initial 5 character and giving the space and click my paste button. So the "HEY" content will be append in that position.

My code:

renderValue = () => {
 var textNode = document.createTextNode("HEY");
      let p1 = document.getElementById('work').focus();
      p1.appendChild(textNode)
}

render(){
<button onClick={() => this.renderValue()}>Paste</button>
<div id="work" onClick={(e)=>e.stopPropagation()}  
contentEditable 
onInput={this.emitChange}
dangerouslySetInnerHTML={{__html: this.props.html}}
>
</div>
}

I have tried to append the text but not getting luck.

Anny help is really appreciated. Thanks in advance.

1

There are 1 best solutions below

1
On

You can use document.execCommand() with insertText command. Like

document.execCommand("insertText", false, "HEY!!")