4

I need a react component that will allow me to display a text for which I can easily capture the selected text region, and then create nested spans inside it (to, e.g. highlight text regions). The spans should then be able to be managed independently (with their own "onclick" actions, for example).

I understand this is a very specific behaviour. My goal is not to ask whether there is a component that can meet all my requisites, but whether there is something that can be used as a base to get most of this behaviour in a more or less straightforward way (that is, without having to manually deal with <p>'s and document.getSelection()). Does something like this exist?

Setzer22
  • 1,589
  • 2
  • 13
  • 29
  • Thank you all for your answers, it seems that indeed doing what I needed was no simple matter. In the end, I figured out I needed something that rendered actual squares on top of the highlighted characters, so I used absolute-positioned divs (plus some calculations using paragraph line height and character position). That works very well for my use-case, but I understand this solution is not for everyone, and it a bit hacky to say the least. Once I can release the code I'm working on, I'll take some time and write an answer explaining how I did it for anyone interested. – Setzer22 Sep 26 '18 at 08:38

2 Answers2

1

EDIT: I was able to find this component especifically for that, and on other answers people recommended DraftJS component. The answers are below

OLD --

Searching i was able to find this

Use field.selectionStart example in this answer.

On this answer: Get cursor position (in characters) within a text Input field

It allows you to find where a selection starts on a text field.

I know it isn't a component, but hope it help if you're unable to find one

Also, an example of it on React: How to get the selected text from text area in react?

On this answer the DraftJS Component

1

Don't think that such component is written on React...

This looks like Native JS area, and if you will find library, most likely you will need to create uncontrolled DOM (so react will not update it) and use library to highlight something inside that DOM

Short investigation gives Rangy Highlighter-Module as one of possible options how to implement

DEMO of Rangy Highlighter-Module

Andrii Muzalevskyi
  • 3,261
  • 16
  • 20