Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Detecting which input is focused React hooks

I'm using React Hooks. I want to check which input is focused. I have an object of dynamically generated inputs. The inputs will be selected and I want to have a button that will append a value to the input that is in focus.

like image 257
BubblesTheTurtle Avatar asked Sep 01 '25 10:09

BubblesTheTurtle


1 Answers

(Edit) Updated to a much better solution using React Hook

Most solutions I've come across don't take into account when the form has no active element. Hence I came up with the following hook to cover this case.

const useActiveElement = () => {
  const [listenersReady, setListenersReady] = React.useState(false); /** Useful when working with autoFocus */
  const [activeElement, setActiveElement] = React.useState(document.activeElement);

  React.useEffect(() => {
    const onFocus = (event) => setActiveElement(event.target);
    const onBlur = (event) => setActiveElement(null);

    window.addEventListener("focus", onFocus, true);
    window.addEventListener("blur", onBlur, true);

    setListenersReady(true);

    return () => {
      window.removeEventListener("focus", onFocus);
      window.removeEventListener("blur", onBlur);
    };
  }, []);

  return {
    activeElement,
    listenersReady
  };
};

https://codesandbox.io/s/competent-thunder-59u55?file=/src/Form.js

That should make it easier for you to detect which form input is active.

like image 58
Fappaz Avatar answered Sep 03 '25 23:09

Fappaz