textarea does not auto focus even when set to auto focus

<textarea
  className="input"
  ref={textarea_ref}
  name="the-textarea"
  id="the-textarea"
  maxLength="150"
  placeholder="see guidelines for suggestions..."
  autoFocus
  onChange={(e) => input_text(e.target.value)}
  value={validated_text}
></textarea>

What might be some other factors that will cause the textarea to not auto focus when initialized?

Upvotes: 2

Views: 1440

Answers (1)

Ryan Le
Ryan Le

Reputation: 8412

autofocus is defined to work reliably only on page load

So it might not work as you expected in Reactjs Component where you are changing/updating DOM or open a new Modal.


I would suggest using useRef instead:

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

export default function App() {
  const textarea_ref = useRef();
  useEffect(() => {
    textarea_ref.current.focus();
  });
  return (
    <textarea
      className="input"
      ref={textarea_ref}
      name="the-textarea"
      id="the-textarea"
      maxLength="150"
      placeholder="see guidelines for suggestions..."
    ></textarea>
  );
}

Upvotes: 4

Related Questions