How to get the selected text from text area in react?

狂风中的少年 提交于 2019-11-30 15:54:55

问题


I am trying to make a text editor in react.Does anyone knows how to get the selected text from the textarea so that styles can be applied on the selected text.I know we can use window.getSelection in javascript but I am curious to know If any other methods are available for this functionality?


回答1:


Yes there is a method to do this, specially in React. The way you should go to achieve this is as follow.

step 1:- use ref in your textarea ui element. like

     `<textarea
           className='html-editor'  
           ref='myTextarea' 
          value = {this.state.textareaVal}
          onChange={(event)=>{
                      this.setState({
                         textareaVal:event.target.value;
                      });
                   }}
       >
      </textarea>` 

step 2:- now you can access the DOM element,using react refs.

    let textVal = this.refs.myTextarea; 

step 3:- use selectionStart and selectionEnd :- using selectionStart and
selectionEnd you can get to know your start and end pointer
of selected text.which can be done as below;

        let cursorStart = textVal.selectionStart;
        let cursorEnd = textVal.selectionEnd;

now you have start and end index of your selected text.

step 4 :- use javascript substring function to get the selected text.

    this.state.textareaVal.substring(cursorStart,cursorEnd) 



回答2:


The best way to make a Text Editor in React is to use DraftJS.

If you are using React, DraftJS is the way to go about it. It abstracts away many of the challenges you would face while trying to create your own text editor from scratch. This includes managing the state of your editor (similarly to how you would manage a component's state), managing text selection, applying different attributes and so on.

You can get started by checking out the docs, and I would suggest watching the introduction video on that page, which goes through the difficulties DraftJS aims to solve.

I hope that helps.



来源:https://stackoverflow.com/questions/42619553/how-to-get-the-selected-text-from-text-area-in-react

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!