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

1

1 Answer 1

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>
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.