DEV Community

Bukunmi Odugbesan
Bukunmi Odugbesan

Posted on

Coding Challenge Practice - Question 16

The task is to create a useFocus() hook that allows conditional rendering in parent element to focus on the state of descendant elements.

The boilerplate code is:




import React, { Ref } from 'react'

export function useFocus<T extends HTMLElement>(): [Ref<T>, boolean] {
  // your code here
}

// if you want to try your code on the right panel
// remember to export App() component like below

// export function App() {
//   const [ref, isFocused] = useFocus()
//   return <div>
//     <input ref={ref}/>
//     {isFocused && <p>focused</p>}
//   </div>
// }

Enter fullscreen mode Exit fullscreen mode

The first step is to create a ref for the input, and also a state variable for focusing on the input

const ref = useRef<T>
const[isFocused, setIsFocused] = useState(false)
Enter fullscreen mode Exit fullscreen mode

The state is a boolean because the input is either focused or not. The next step is to get the node. If there is no node, return null.

const node = ref.current
if(!node) return
Enter fullscreen mode Exit fullscreen mode

Next, a function that sets isFocused to true when the focus moves into the container or any descendant

const handleFocusIn = () => setIsFocused(true)
Enter fullscreen mode Exit fullscreen mode

Then, a function that sets isFocused to false when the focus is outside the container or any descendant. It receives the FocusEvent and uses event.relatedTarget to see where focus is moved to.

const handleFocusOut = (e: FocusEvent) => {
 if(node && !node.contains(e.relatedTarget as Node)) {
setIsFocused(false)
}
}
Enter fullscreen mode Exit fullscreen mode

Event listeners for focusin and focusout should be added to the node.

node.addEventListener("focusin", handleFocusIn)
node.addEventListener("focusout", handleFocusOut)
Enter fullscreen mode Exit fullscreen mode

A function to clean up previous event listeners when the app renders again

return () => {
 node.removeEventListeners("focusin", handleFocusIn)
 node.removeEventListeners("focusout", handleFocusOut)
}
Enter fullscreen mode Exit fullscreen mode

The final code with an example looks like this:




import React, { useRef, useEffect, useState, Ref } from 'react'

export function useFocus<T extends HTMLElement>(): [Ref<T>, boolean] {
  // your code here
  const ref = useRef<T>(null);
  const[isFocused, setIsFocused] = useState(false);

  useEffect(() => {
    const node = ref.current
    if(!node) return

    const handleFocusIn = () => setIsFocused(true);
    const handleFocusOut = (e: FocusEvent) => {
      if(node && !node.contains(e.relatedTarget as Node)) {
        setIsFocused(false)
      }
    }

    node.addEventListener("focusin", handleFocusIn)
    node.addEventListener("focusout", handleFocusOut)

    return () => {
      node.removeEventListener("focusin", handleFocusIn)
      node.removeEventListener("focusout", handleFocusOut)
    }
  })
  return [ref, isFocused]
}

// if you want to try your code on the right panel
// remember to export App() component like below

export function App() {
  const [ref, isFocused] = useFocus<HTMLDivElement>()
  return <div ref={ref}>
    <input placeholder="First Input"/>
    <input placeholder="Second Input" />
    {isFocused && <p>focused</p>}
  </div>
}

Enter fullscreen mode Exit fullscreen mode

That's all folks!

Top comments (0)