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

后端 未结 2 1032
难免孤独
难免孤独 2021-01-03 00:43

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

2条回答
  •  天涯浪人
    2021-01-03 01:31

    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

         `` 
    

    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) 
    

提交回复
热议问题