javascripthtmlreactjstypescriptrich-text-editor

Why does editable-div move the cursor to front of div


<div className="min-w-[600px] min-h-[36.8px]" >
                 <div id={`editableDiv-${Object.keys(item)}-${index}`} className="p-3" contentEditable suppressContentEditableWarning onInput={(e) => onChange(e)} >
                  {Object.values(item)}
              </div>

Using the code above for editable-div, when onInput is triggered, the index keeps on moving to the front of the div. E.g. when I type 'fruit' it becomes 'tiurf'

 <div className="min-w-[600px] min-h-[36.8px]" >
                 <div id={`editableDiv-${Object.keys(item)}-${index}`} className="p-3" contentEditable suppressContentEditableWarning onInput={() => onChange} >
                  {Object.values(item)}
              </div>

I used this code before, which worked. However, it stopped triggering onInput.

const onChange = (e: any) => {
    console.log(1)
    let targetId = e.currentTarget.id
    let objectContent = e.currentTarget.textContent
    let checkIndex = parseInt(targetId.split('-')[2])
    let checkTitle = targetId.split('-')[1]
    let newArr = [...content]
    newArr[checkIndex][checkTitle] = objectContent
    setContent(newArr)
    updateData(content)
  } 

This is the onChange function that is being triggered.

It works as usual when onInput is not triggered and is not managed in an object using state. However, when the onInput is triggered for the div it starts moving the cursor to the front.


Solution

  • It happened because every time I changed the data inside the editable-div the state changed, and the page re-rendered resulting in the cursor moving to the front.

    So instead of using useState, using useRef will not re-render the page, giving the continuous writing flow.

    p.s. Any re-render will move the cursor to front.