You need to grab the first and last indices, and figure out the words from there.
const [highlightStart, setHighlightStartIndex] = useState();
const [highlightEnd, setHighlightEnd] = useState();
const paragraph = "some text in paragraph blah blah blah";
const paragraphArr = paragraph.split(" ").map((word, index) => (
<span
key={index}
id={`paragraph_${index}`}
onMouseDown={(e) => handleHighlightStart(index)}
onMouseUp={(e) => handleHighlightEnd(index)}
>
{word}{" "}
</span>
));
const handleHighlightStart = (index) => {
console.log("highlightStart", index);
setHighlightIndexStart(index + 1); //because start word is the one after cursor starts
};
const handleHighlightEnd = (index) => {
console.log("highlightEnd", index);
setHighlightIndexEnd(index - 1); //because end word is the last one before cursor ends
};
You can figure out the selected text from the indices. You would also need to take care of cases when the user highlights backward.