1.0.1 • Published 3 years ago

usefocuswithin v1.0.1

Weekly downloads
-
License
-
Repository
github
Last release
3 years ago

usefocuswithin

React Hook to detect if an element or its descendent element has focus. Similar to css :focus-within pseudo-class behaviour.

Currently, only change of focus with mouse 'click' event is processed. If focus is changed with Tab or any other means then the isFocusWithin will not update.

Live Demo

Edit usefocuswithin

Installation

npm

npm install usefocuswithin

yarn

yarn add usefocuswithin

Usage

import React from "react";
import { usefocuswithin } from "usefocuswithin";

function App() {
  const targetRef = React.useRef(null);
  const isFocusWithin = usefocuswithin(targetRef);

  return (
    <div
      ref={targetRef}
      style={{ border: `1px solid ${isFocusWithin ? "green" : "red"}` }}
    >
      <input></input>
    </div>
  );
}

API

usefocuswithin(target, options?)

Arguments

ArgumentTypeRequired?Description
targetReact.RefObject | T | nullYesA React ref created by useRef() or an HTML element
optionsObjectYesConfiguration options for the hook. See Options below.

Returns boolean

This hook returns true if the element in ref or any of its descendent element is focused, otherwise false.

Options

PropertyTypeDescription
mousebooleanDetects change of focus due to mouse click event.
keyboardbooleanDetects change of focus due to Tab keypress on keyboard.