1

I'm trying to trigger focus event programatically:

import { useRef } from "react";
import "./styles.css";

export default function App() {
  const ref = useRef();

  function focusTrig() {
    ref.current.focus();
  }
  
  return (
    <div className="App">
      <h1>Hello CodeSandbox</h1>
      <h2>Start editing to see some magic happen!</h2>

      <button onClick={focusTrig}>Focus trigger</button>

      <div ref={ref} onFocus={() => console.log("FOCUSED!")}>
        Focus Target
      </div>
    </div>
  );
}

demo

The console.log binded with the onFocus event never run. Why?

UPDATE If I turn the target element from DIV to INPUT, the the console.log get run. But this openly conflicts with the official documentation, that states:

These focus events work on all elements in the React DOM, not just form elements.

ReactJS 17 DOC

Nemus
  • 1,322
  • 2
  • 23
  • 47
  • see if this answers your question https://stackoverflow.com/questions/43145549/how-react-programmatically-focus-input – Dante_97 Aug 25 '22 at 14:33

1 Answers1

1

Add tabIndex to the div element which indicates that it can be focused

<div tabIndex="0" ref={ref} onFocus={() => {console.log("FOCUSED!")}}>
        Focus Target
      </div>
monim
  • 3,641
  • 2
  • 10
  • 25