I would like to show the user a paragraph of text, and then ask the user to select part(s) of text. This text will then be analysed and an output will be shown in another component. How can I achieve this in Dash? This question is similar to this already answered question (Can Shiny recognise text selection with mouse (highlighted text)?), which solves the problem in Shiny.
How to acquire the text selected with mouse (highlighted text)?
470 views Asked by Sainath Adapa At
1
We can detect whether text is selected by adding event listeners in Javascript.
We are, at the time I'm writing this, limited in terms of the communication that is possible between Dash components and Javascript. Clientside callbacks allow us to execute Javascript code inside callbacks. We can't really use those here, because there isn't really a suitable
Input
we can use for detecting when text is highlighted.We can instead create a custom Dash component with React that listens for a
selectionchange
event:I've created the following custom component that allows us to detect when text is selected and persists this to a property so it can be used in Dash callbacks:
See this answer and the documentation here for more on creating custom Dash components with React.
A demo that shows how you could use this custom component in a Dash app:
The
selectedValue
property holds the value of what is currently selected in the document.Everytime the selection changes this callback is executed.
I've put up this code on Github here and on pypi here.
If you want to use my package you can install it with
pip install dash-selectable
.