Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 293
akila arasan Avatar asked Mar 06 '17 07:03

akila arasan


People also ask

How do I get the selected text option in react?

How do you get selected option text in react JS? The text of an option is simply the label property of the corresponding item . In your case, to retrieve the text of the selected option, you can do: var selectedItem = this.

What is ${} In react?

the ${} is the syntax for variables (or other code to be executed) inside template literals (`).

How do you select an item in react?

To select a default option in React, the selected attribute is used in the option element. In React, though, instead of using the selected attribute, the value prop is used on the root select element. So, you can set a default value by passing the value of the option in the value prop of the select input element.


1 Answers

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) 
like image 140
sanjeev Avatar answered Oct 02 '22 14:10

sanjeev