javascript - How can you get highlighted text (window.getSelection()) in ReactJS - Stack Overflow

I have been learning to make a custom markdown editor. However I just ran into the problem of getting t

I have been learning to make a custom markdown editor. However I just ran into the problem of getting the highlighted text before wrapping it with the markdowns. Here's my example

class TextArea extends React.Component {
    constructor(props){
    super(props);
    this.state = {
        ment:'He oppose at thrown desire of no. Announcing impression unaffected day his are unreserved indulgence.She oppose at thrown desire of no..'
    };
    this.onClickMakeBold = this.onClickMakeBold.bind(this);
  }

  render(){
    return <div>
       <button onClick={this.onClickMakeBold}>Bold</button> 
         <div>
           <textarea ref="textarea">{this.statement}</textarea>
        </div>
    </div>
  }

  onClickMakeBold(){
    console.log(getSelectionText()) 
  }
}
function getSelectionText() {
    var text = "";
    if (window.getSelection) {
        text = window.getSelection().toString();
    } else if (document.selection && document.selection.type != "Control"){
        text = document.selection.createRange().text;
    }else{
            alert('no')
    }
    return text;
}

React.render(<TextArea />, document.getElementById('container'));

The result from getSelectionText() function doesn't return any text at all. How can I get the highlighted text in ReactJS?

I have been learning to make a custom markdown editor. However I just ran into the problem of getting the highlighted text before wrapping it with the markdowns. Here's my example

class TextArea extends React.Component {
    constructor(props){
    super(props);
    this.state = {
        ment:'He oppose at thrown desire of no. Announcing impression unaffected day his are unreserved indulgence.She oppose at thrown desire of no..'
    };
    this.onClickMakeBold = this.onClickMakeBold.bind(this);
  }

  render(){
    return <div>
       <button onClick={this.onClickMakeBold}>Bold</button> 
         <div>
           <textarea ref="textarea">{this.state.ment}</textarea>
        </div>
    </div>
  }

  onClickMakeBold(){
    console.log(getSelectionText()) 
  }
}
function getSelectionText() {
    var text = "";
    if (window.getSelection) {
        text = window.getSelection().toString();
    } else if (document.selection && document.selection.type != "Control"){
        text = document.selection.createRange().text;
    }else{
            alert('no')
    }
    return text;
}

React.render(<TextArea />, document.getElementById('container'));

The result from getSelectionText() function doesn't return any text at all. How can I get the highlighted text in ReactJS?

Share Improve this question edited Aug 7, 2016 at 4:10 RedGiant asked Aug 7, 2016 at 4:03 RedGiantRedGiant 4,74911 gold badges63 silver badges151 bronze badges 1
  • You should try DraftJS, super cool editor from Facebook. – vijayst Commented Aug 7, 2016 at 5:47
Add a ment  | 

2 Answers 2

Reset to default 4

By clicking on the button, you deselect the text before the event is triggered.

Pass the callback to your button as onMouseDown, as this event happens before the standard click side effects take place.

Also: if you want the text to remain selected after the event has been processed, use event.preventDefault() in your callback function.

here is solution with react hook pure without any library!

to clone and the small package or any question you can check: https://github./Farbod29/React-text-highlighter-with-hook-

import React, { useState, useEffect } from 'react';
import './highlight.css';

export default function Highlighter() {
  const [highlightedText, setHighlightedText] = useState(
    'highlighted text will be shown here!'
  );
  useEffect(() => {
    const saveSelection = () => {
      setHighlightedText(window.getSelection().toString());
    };
    document.addEventListener('mouseup', saveSelection);
    return () => document.removeEventListener('mouseup', saveSelection);
  }, []);
  return (
    <>
      <section className="card">
        <div>
          <div className="margin-top-zero txt">
            Here is react text highlighter with hook and use state/Effect, 
            understand if you have any question just email or add issue in above git ripo!
         
          </div>
          {/* {ghasem} */}
          <div className="txt">{highlightedText}</div>
          <div // parent of button
          >
            <button className="btn"> Add Highlighted text </button>
          </div>
        </div>
      </section>
    </>
  );
}

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744306663a4567746.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信