React JS - insert text in the middle of textarea

React JS - insert text in the middle of textarea

Post by: Niraj Dhungana

Posted on: Nov 23, 2021

#React# textarea

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.

1
npx create-react-app cool-textarea

Now we need a textarea. I will add this inside the App component.

1
2
3
4
5
6
7
8
export default function App() {
  return (
    <div>
      <button>Add some text</button>
      <textarea></textarea>
    </div>
  );
}

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 😜.

We can add a `state` and update that `state` with the appended value at the beginning or end. Like this.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
export default function App() {
  const [value, setValue] = useState("");

  // insert value before and after inside textarea.
  const addSomeText = () => {
    let newValue = "Inserted value Before " + value + " inserted value after";
    setValue(newValue);
  };

return (
    <div className="container">
      <button onClick={addSomeText}>Add some text</button>
...
)}

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 setUserInput.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
export default function App() {
  const [value, setValue] = useState("");
  const [userInput, setUserInput] = useState("");

  const insertSomeText = () => {  };

  return (
    <div className="container">
      <input
        placeholder="Text to insert"
        value={userInput}
        onChange={({ target }) => setUserInput(target.value)}
      />
...
  );
}

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.

1
2
3
4
5
6
7
8
9
10
11
export default function App() {
  const textareaRef = useRef();

  return (
        ...
      <textarea
        ref={textareaRef}
       ...
  );
}

Inside javascript we can use textarea.selectionStart/End to find out the selection area of the text. So, let’s use that with the textareaRef we just created.

1
2
3
4
5
6
const insertSomeText = () => {
    const selectionStart = textareaRef.current.selectionStart;
    const selectionEnd = textareaRef.current.selectionEnd;

    console.log(selectionStart, selectionEnd)
};

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).

result of the selected text inside console

We have the start and the end of our selection. Let’s use the substring method and combine all of the things together.

1
2
3
4
5
6
7
8
9
10
const insertSomeText = () => {
   const selectionStart = textareaRef.current.selectionStart;
   const selectionEnd = textareaRef.current.selectionEnd;

   let newValue =
     value.substring(0, selectionStart) +
     userInput +
     value.substring(selectionEnd, value.length);
   setValue(newValue);
};

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.