Select Text & highlight selection or get selection value (React)

后端 未结 6 1237
长发绾君心
长发绾君心 2021-02-02 02:33

I have a React application which displays some spans:

Hello my name  is &l         


        
相关标签:
6条回答
  • 2021-02-02 02:51

    Step 1: - Initially Mouse will capture every time you enter something

    <textarea type="text" 
              className="contentarea__form__input" 
              onMouseUpCapture={this.selectedText}>
    </textarea>
    

    Step 2: To make sure it only catches your selected text I used if-else condition

    selectedText = () => {
        window.getSelection().toString() ? console.log(window.getSelection().toString()) : null;
    }
    
    0 讨论(0)
  • 2021-02-02 02:52

    Use onMouseUp and onDoubleClick events to detect to call method, that will determine selection using JavaScript Selection API.

    Use window.getSelection() to get selection object.

    To get selected text, use window.getSelection.toString().

    To get coordinates of selected text area for rendering popup menu, use selection.getRangeAt(0).getBoundingClientRect().

    As an example implementation, take a look at react-highlight library.

    0 讨论(0)
  • 2021-02-02 02:52

    Due to this bug in Firefox, I was unable to get it working with window.getSelection() as suggested by other answers.

    So I had to do the following (in React):

    constructor(props) {
        this.textAreaRef = React.createRef();
    }
    
    getSelection() {
        const textArea = (this.textAreaRef.current as HTMLTextAreaElement);
        console.log(textArea.value.substring(
                textArea.selectionStart,
                textArea.selectionEnd
            )
        );
    }
    
    render() {
        <textarea onMouseUp={() => this.getSelection()}
                            ref={this.textAreaRef}>
        </textarea>
    }
    
    0 讨论(0)
  • 2021-02-02 02:54

    Here's an example in React using a functional component:

    const Post = () => {
        const handleMouseUp() {
            console.log(`Selected text: ${window.getSelection().toString()}`);
        }
        return (
            <div onMouseUp={handleMouseUp}>Text</div>
        );
    }
    

    As Lyubomir pointed out the window.getSelection() API does the trick!

    0 讨论(0)
  • 2021-02-02 02:57

    There is no React-specific solution for this. Just use window.getSelection API.


    To output highlighted text run window.getSelection().toString()

    0 讨论(0)
  • 2021-02-02 03:10

    I think that it's the right way...

     document.onmouseup = () => {
       console.log(window.getSelection().toString());
     };
    
    0 讨论(0)
提交回复
热议问题