In order to know whether an element is currently focused, we can use the useFocus Hook as follows:
- First, we import the useFocus Hook:
import React from 'react'
import { useFocus } from 'react-hookedup'
- Then, we define our component and the Focus Hook, which returns the focused value and a bind function, to bind the Hook to an element:
export default function UseFocus () {
const { focused, bind } = useFocus()
- Finally, we render an input field, and bind the Focus Hook to it:
return (
<div>
<input {...bind} value={focused ? 'focused' : 'not focused'} />
</div>
)
}
As we can see, the Focus Hook makes it much easier to handle focus events. There is no need to define our own handler functions anymore.