I'm trying to create a text editor and I'm using a contenteditable
div and everytime someone changes the text inside it I want to wrrap all that new text with a strong
element and change the div's innerHTML
This is what I tried (I'm using react/nextjs)
useEffect(() => {
if (!divRef.current) return;
let text = divRef.current.innerText;
const htmlArray = text.split(" ").map((word) => {
return `<strong style="color: red">${word} </strong>`;
});
text = htmlArray.join("");
divRef.current.innerHTML = text;
}, [text]);
everything here works as expected but everytime I type a character the cursor goes to the start and the text is rendered backwards. How can I fix the issue I want the cursor to stay an the end of the div when user type