Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Insert text at cursor position in React

Tags:

reactjs

I have a textarea that I would like to insert text into at the cursor position when a user clicks a button. Does anyone know how to go about that?

like image 742
Dev01 Avatar asked Jul 16 '26 03:07

Dev01


1 Answers

Qwertie is of course right. Anyway, if you want to insert a given string into a textarea at the cursor position you could use a function like this:

 insertMyText = e => {
      let textToInsert = " this is the inserted text "
      let cursorPosition = e.target.selectionStart
      let textBeforeCursorPosition = e.target.value.substring(0, cursorPosition)
      let textAfterCursorPosition = e.target.value.substring(cursorPosition, e.target.value.length)
      e.target.value = textBeforeCursorPosition + textToInsert + textAfterCursorPosition
    }

and:

<textarea onClick={this.insertMyText}>bla bla bla bla</textarea>
like image 66
Fpunkt Avatar answered Jul 17 '26 16:07

Fpunkt



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!