JSFiddle - React, Tailwind, and code Playground
HTML
<div contenteditable="true">
Press return in here
</div>
JavaScript
document.onkeypress = function(e) {
var sel, textRange;
if (e.which == 13) {
e.preventDefault();
if (document.body.createTextRange) {
try {
document.execCommand("ms-beginUndoUnit", false, null);
} catch (e) {}
if (document.selection) {
textRange = document.selection.createRange();
} else if (window.getSelection) {
sel = window.getSelection();
var range = sel.getRangeAt(0);
// Create a temporary element to allow us to move a TextRange to the correct place
var tempEl = document.createElement("span");
tempEl.innerHTML = "&#FEFF;";
range.deleteContents();
range.insertNode(tempEl);
textRange = document.body.createTextRange();
textRange.moveToElementText(tempEl);
tempEl.parentNode.removeChild(tempEl);
}
textRange.text = "\r\n";
textRange.collapse(false);
textRange.select();
try {
document.execCommand("ms-endUndoUnit", false, null);
} catch (e) {}
} else {
document.execCommand("insertText", false, "\n");
}
}
};