Skip to content

mkamalkayani/usefocuswithin

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

4 Commits
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

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

Argument Type Required? Description
target React.RefObject | T | null Yes A React ref created by useRef() or an HTML element
options Object Yes Configuration 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

Property Type Description
mouse boolean Detects change of focus due to mouse click event.
keyboard boolean Detects change of focus due to Tab keypress on keyboard.

About

React Hook to detect if an element or its descendent element has focus.

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published