usefocuswithin
v1.0.1
Published
React Hook to detect if an element or its descendent element has focus. Similar to css [`:focus-within`](https://developer.mozilla.org/en-US/docs/Web/CSS/:focus-within) pseudo-class behaviour.
Downloads
54
Maintainers
Readme
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.
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. |