javascripthtmlreactjselectron

Select Text & highlight selection or get selection value (React)


I have a React application which displays some spans:

<span>Hello</span> <span>my</span> <span>name</span> <span> is </span> ...

I would like the user to select the text with the mouse like so Hello my Name is

..and then get the selected value, or highlight the text etc. How would I do this in React? I am not sure what event handlers to use and how to get hold of the current selection! A minimal example or a hint would be appreciated!


Solution

  • There is no React-specific solution for this. Just use window.getSelection API.


    To output highlighted text run window.getSelection().toString()