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.
npm install usefocuswithin
yarn add usefocuswithin
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>
);
}
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. |
This hook returns true
if the element in ref
or any of its descendent element is focused, otherwise false
.
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. |