How to edit selected text from a text area?

I am trying to make a text editor in reaction. Does anyone know how to get selected text from a text box so that styles can be applied to the selected text. I know that we can use window.getSelection in javascript, but I am curious to know if any other methods are available for this function?

+1
source share
2 answers

Yes, there is a way to do this, especially in React. How you should do this is to follow.

Step 1: - use ref in the textarea ui element. as

`<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 the ref reaction.

  let textVal = this.refs.myTextarea; 

Step 3: - use selectStart and selectionEnd: - using selectionStart and
selectionEnd you can find your start and end pointer
selected text. This can be done as shown below:

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

You now have the start and end index of the selected text.

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

  this.state.textareaVal.substring(cursorStart,cursorEnd) 
+4
source

The best way to make a text editor in React is to use DraftJS .

If you use React, DraftJS is a way around this. It abstracts out many of the problems you will encounter when trying to create your own text editor from scratch. This includes managing the state of your editor (similar to how you control the state of a component), controlling text selection, applying different attributes, etc.

You can start by checking the documents , and I would suggest watching a video on this page, which is connected with the difficulties DraftJS seeks to solve.

I hope this helps.

+1
source

Source: https://habr.com/ru/post/1275628/


All Articles