JSFiddle - React, Tailwind, and code Playground
HTML
<div contentEditable id="input"></div>
CSS
#input {
border: 3px solid #07c;
width: 300px;
height: 200px;
white-space: pre;
}
JavaScript
var input = $( '#input' )[0];
$( input ).keypress( function ( e ) {
var sel, node, offset, text, textBefore, textAfter, range;
// the Selection object
sel = window.getSelection();
// the node that contains the caret
node = sel.anchorNode;
// if ENTER was pressed while the caret was inside the input field
if ( node.parentNode === input && e.keyCode === 13 ) {
// prevent the browsers from inserting <div>, <p>, or <br> on their own
e.preventDefault();
// the caret position inside the node
offset = sel.anchorOffset;
// insert a '\n' character at that position
text = node.textContent;
textBefore = text.slice( 0, offset );
textAfter = text.slice( offset ) || ' ';
node.textContent = textBefore + '\n' + textAfter;
// position the caret after that new-line character
range = document.createRange();
range.setStart( node, offset + 1 );
range.setEnd( node, offset + 1 );
// update the selection
sel.removeAllRanges();
sel.addRange( range );
}
});