← coderrocketfuel.com

Programmatically Focus a Textarea Element in React.js

How can you programmatically focus a textarea element in React.js? And how could you do that automatically when the page loads?

You can achieve this using React's useRef method:

import React, { useRef } from "react";

export default function Page() {
  const textareaRef = useRef(null);

  function focusTextarea() {
    textareaRef.current.focus();
  }

  return (
    <textarea ref={textareaRef} />
  );
}

The textareaRef creates a reference to the <textarea> element.

Using that, we can apply the focus() to it. Which will change the textarea to have a focused state.

Whenever the focusTextarea() is called, it will focus the <textarea>.

As an example, you could focus the <textarea> when the page is loaded:

import React, { useRef, useEffect } from "react";

export default function Page() {
  const textareaRef = useRef(null);

  useEffect(() => {
    focusTextarea();
  });

  function focusTextarea() {
    textareaRef.current.focus();
  }

  return (
    <textarea ref={textareaRef} />
  );
}

useEffect() will apply the focus via the focusTextarea() function when page is loaded.

Thanks for reading and happy coding!