1

I have a paragraph with some text that I am showing to a user. How do I detect the word that the user clicks on within the paragraph? For example, if a user clicks 'green' on a page, how could I detect that they specifically clicked on 'green'?

const str = 'The sky is blue. The grass is green. The stop sign is red.'

const handleClick = () => {
  alert(e.target.value);
}

const Content = () => {
  return (
    <div>
      <p onClick={handleClick()}>{str}</p>
    </div>
  );
};
arctic
  • 609
  • 3
  • 11
  • 19
  • Does this post answer your question? https://stackoverflow.com/questions/7563169/detect-which-word-has-been-clicked-on-within-a-text – Cybershadow May 05 '21 at 19:30
  • Does this answer your question? [Detect which word has been clicked on within a text](https://stackoverflow.com/questions/7563169/detect-which-word-has-been-clicked-on-within-a-text) – Daniel Beck May 05 '21 at 19:30
  • You might need to split the string. Put it in separate span's and and onClick on each of them. – M S May 05 '21 at 19:31
  • https://stackoverflow.com/a/51615812/14104 – epascarello May 05 '21 at 19:31
  • @DanielBeck @Cybershadow No. I cannot use `s.modify()` in React. Further, I dont think DOM manipulation is recommended in React outside of the framework. – arctic May 05 '21 at 19:41
  • 1
    Not sure what you mean. Seems to be working https://jsfiddle.net/xg51qfvu/1/ – Cybershadow May 05 '21 at 20:01
  • DOM manipulation is to be avoided, yes; but reading from `window.getSelection()` is not manipulating the DOM. (`Selection.modify()` is not necessary; it was only mentioned in passing in one of the answers on the linked question.) – Daniel Beck May 05 '21 at 20:33

1 Answers1

1

Something like this...

const str = 'The sky is blue. The grass is green. The stop sign is red.'

const handleClick = (s) => {
    alert(s);
}

return (
    <div>
        {
            str.split(' ').map(s => {
                return <span onClick={() => handleClick(s)}>{s}&nbsp;</span>
            })
        }
    </div>
);
Bafsky
  • 761
  • 1
  • 7
  • 16