'Determine when text selection changes for non-input element in React?

Is there a react input handler that will notify me when the text selection on a particular div in a document changes.

I know of onSelect, but that only works in inputs and textareas.

Context: I'm writing a custom PDF viewer using PDF.js + React. I am trying to figure out whenever the selection of text on the PDF document changes.

So far, I haven't found an easy way to do this.



Solution 1:[1]

You can use a onmouseup event, and check if text is selected, as you need to release the mouse after selecting text.

const e = React.createElement;

function App() {
  let lastSelect = "";
  function mouse(evt) {
    console.log("New Mouse Up");
    const selected = document.getSelection().toString();
    if (selected !== lastSelect) console.log("New Selection", selected);
    else console.log("Old Selection", selected)
  }

  return e("div", { onMouseUp: mouse }, "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Duis euismod libero at nibh dapibus, eget tincidunt eros porta. Aenean luctus fermentum turpis, eget consequat odio hendrerit at. Curabitur gravida, dolor porta aliquet vulputate, enim odio interdum nisi, et malesuada metus ante ut nisi.")
}

ReactDOM.render(e(App), document.querySelector(".root"));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
<div class="root"></div>

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 sean-7777