Search code examples
javascriptreactjsnpminputselection-api

How can I access current cursor location using npm package react-mentions


I'm currently trying to track the event.target.selectionStart and event.target.selectionEnd for a react-mentions component using an onchange handler. How can I get access to selectionStart and selectionEnd of this input?

<MentionsInput
    value={value}
    onChange={handleChange}
    placeholder={placeholder}
  >
<Mentions/>
<Mentions2/>

handleChange(e){
  console.log(e)//just object with one key: target
  console.log(e.target.value) //returns value
  console.log(e.target) //object with key value pair for "value": [value]
  console.log(e.target.selectionStart) //undefined
  console.log(e.target.selectionEnd) //undefined
}

references: https://github.com/signavio/react-mentions insert at cursor in react


Solution

  • Technically what you're trying to do is access the caret location.

    Assuming your application has only one selection at a time, which is almost always the case, you can get it using window.getSelection() and reference the focusOffset and focusNode properties of the result.

    I don't know if you can get the anchor/focus offsets directly from the event's target, but I don't think so.

    If you want to add some extra safeguarding you can ensure that the anchorNode matches the element from the event.target - although with fancy things like this with React, sometimes the target of the event will not actually be the element that's currently in the window's selection.