React JS - insert text in the middle of textarea
Post by: Niraj Dhungana
Posted on: Nov 23 2021
Sometimes you need weird things while coding. Like here I will show you one weird thing. How to insert a text in the middle of other text inside the HTML
textarea inside React JS.
You can check out the demo here.
First let’s create a react app if you haven't already. If you already have a project then you can skip these steps.
Now we need a textarea. I will add this inside the
Now our cool
textarea is ready. Let’s add some text when we click that
button. If you just want to add some text at the end or at the beginning of your textarea that’s easiestly simple 😜.
Now with this code will add some text before and after as the value of
textarea. Check out the final result here.
Okay, let's see how we can insert text in the middle of the textarea where your cursor is or in the middle of the text you selected.
For that, first I will add a text
input, a new state called
userInput and a method called
insertSomeText. Also we have that
onChange where we are updating the user input using
Now we have the desired text to insert inside
textarea. It’s time to figure out where our cursor is inside the textarea. For that we need to create a reference of the
textarea.selectionStart/End to find out the selection area of the text. So, let’s use that with the
textareaRef we just created.
Now if you select some text from inside that
textarea or just place a cursor in the middle and click that
button it will log the exact position of your selection (start and end).
We have the start and the end of our selection. Let’s use the
substring method and combine all of the things together.
Now ladies and gentlemen if you add some value inside the input field and press that Add some text button. That text will be added wherever your cursor is. If you want to check the demo go up.