This solution is generated by ChatGPT, correctness is not guaranteed. You might also be able to find a solution fromcommunity postsor official solution page.
AI solution for React Coding Question on BFE.dev
11. useFocus()
import { useState, useEffect, useRef } from "react";function useFocus() { const ref = useRef(null); const [isFocused, setIsFocused] = useState(false); const handleFocus = () => setIsFocused(true); const handleBlur = () => setIsFocused(false); useEffect(() => { if (ref.current) { const element = ref.current; element.addEventListener("focus", handleFocus); element.addEventListener("blur", handleBlur); return () => { element.removeEventListener("focus", handleFocus); element.removeEventListener("blur", handleBlur); }; } }, [ref]); return [ref, isFocused];}function App() { const [ref, isFocused] = useFocus(); return ( <div> <input ref={ref} /> {isFocused && <p>focused</p>} </div> );}
The useFocus()
hook uses useRef
to create a reference to the element we want to check for focus. It also uses useState
to track whether the element is currently focused or not.
useEffect
is used to add event listeners for "focus" and "blur" events, which then update the state accordingly.
Finally, useFocus()
returns an array with the reference to the element and the state of whether it's focused or not, enabling us to use it in the App
component.