javascriptreactjsdomnext.jscontenteditable

How to put new lines in p tag in contentEditable div


I have a contentEditable div, whenever I insert a new line by pressing enter or shift+enter the new line is a textNode in the div but I want the new line to be in p element.

I want a simple solution

I am using React Js so I save the content of contentEditable div in a state named content updated by onChange and I'm using react-contenteditable component package


Solution

  •     const insertNewLine = (e) => {
            if (e.key === 'Enter') {
                e.preventDefault();
    
                // Create a new <p> element
                const newParagraph = document.createElement('p');
                newParagraph.innerHTML = '<br>'; // Add a line break to make the new paragraph visible
    
                // Insert the new <p> element after the current selection
                const selection = window.getSelection();
                const range = selection.getRangeAt(0);
                range.deleteContents();
                range.insertNode(newParagraph);
    
                // Move the caret inside the new <p> element
                const newRange = document.createRange();
                newRange.setStart(newParagraph, 0);
                newRange.setEnd(newParagraph, 0);
                selection.removeAllRanges();
                selection.addRange(newRange);
            }
        };