Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
82
rated 0 times [  87] [ 5]  / answers: 1 / hits: 43376  / 7 Years ago, wed, may 31, 2017, 12:00:00

Does React have an event handler for the onSelect statement? i.e. if a user selects some text with their mouse within a paragraph (highlighted text) trigger an event that extracts the selected text.



import React, { Component } from 'react';

class ReadModule extends Component {
selectedText() {
console.log(You selected some text);
}

render() {
return (
<div id=read-module className=row>
<p>Reading:</p>
<span onSelect={this.selectedText}>{this.props.reading}</span>
</div>
);
}
}

export default ReadModule;


The above doesn't work. If there is an approach that is better i.e. extracting a string please do let me know! Once i get a simple




on highlight trigger function




Concept working I can take it from there. Thanks in advance



Solution:



import React, { Component } from 'react';

class ReadModule extends Component {
selectedText() {
var txt = ;
if (window.getSelection) {
txt = window.getSelection();
}
else if (document.getSelection) {
txt = document.getSelection();
} else if (document.selection) {
txt = document.selection.createRange().text;
}

alert(Selected text is + txt);
}

render() {
return (
<div id=read-module className=row>
<p>Reading:</p>
<span onMouseUp={this.selectedText}>{this.props.reading}</span>
</div>
);
}
}

export default ReadModule;

More From » reactjs

 Answers
22

Check out https://github.com/ydeshayes/react-highlight



To get the effect you want with a regular DOM element involves a lot of delicate code handling mouse events.



You could cheat and use an <input> or <textarea> instead and style it to look like regular text. Then onSelect should just work.


[#57616] Saturday, May 27, 2017, 7 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
bryantc

Total Points: 455
Total Questions: 96
Total Answers: 110

Location: San Marino
Member since Thu, Jun 30, 2022
2 Years ago
bryantc questions
Fri, Aug 13, 21, 00:00, 3 Years ago
Tue, Mar 30, 21, 00:00, 3 Years ago
Fri, Jun 5, 20, 00:00, 4 Years ago
Wed, May 27, 20, 00:00, 4 Years ago
;