Skip to main content

useFocus

React Sensor Hooks that tracks element foucs state

Usage

Live Editor

function Demo() {
  const text = useRef<HTMLParagraphElement>(null);
  const input = useRef<HTMLInputElement>(null);
  const button = useRef<HTMLButtonElement>(null);

  const [paragraphFocus, setParagraphFocus] = useFocus(text);
  const [inputFocus, setInputFocus] = useFocus(input, true);
  const [buttonFocus, setButtonFocus] = useFocus(button);
  return (
    <div>
      <p ref={text} style={paragraphFocus ? { opacity: 0.5 } : {}} tabIndex={0}>
        Paragraph that can be focused
      </p>
      <input ref={input} placeholder="Input that can be focused" />
      <br />
      <br />
      <button ref={button} style={buttonFocus ? { opacity: 0.5 } : {}}>
        Button that can be focused
      </button>
      <br />
      <br />
      <hr />
      <p style={{ height: "2rem" }}>
        {paragraphFocus && "The paragraph has focus"}
        {inputFocus && "The input control has focus"}
        {buttonFocus && "The button has focus"}
      </p>
      <div>
        <button
          onClick={() => {
            setParagraphFocus(!paragraphFocus);
          }}
        >
          Focus text
        </button>
        <button
          onClick={() => {
            setInputFocus(!inputFocus);
          }}
        >
          Focus input
        </button>
        <button
          onClick={() => {
            setButtonFocus(!buttonFocus);
          }}
        >
          Focus button
        </button>
      </div>
    </div>
  );
};

Result
Loading...

API

useFocus

Returns

readonly [boolean, (value: boolean) => void]: A tuple with the following elements:

  • whether the element focus.
  • A function to update focus state.

Arguments

ArgumentDescriptionTypeDefaultValue
targetdom elementBasicTarget<HTMLElement | SVGElement> (Required)-
initialValuedefaultValueboolean | undefinedfalse

BasicTarget

export type BasicTarget<T extends TargetType = Element> = (() => TargetValue<T>) | TargetValue<T> | MutableRefObject<TargetValue<T>>;

TargetValue

type TargetValue<T> = T | undefined | null;

TargetType

type TargetType = HTMLElement | Element | Window | Document | EventTarget;