Create a useHover hook that shows conditional rendering of the hover state of some element.
The boilerplate code:
import { Ref } from 'react'
export function useHover<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() {
// return <div>your app</div>
// }
The first step is to create a ref for the hovered element and a state variable for the hovered state.
const ref = useRef<T>()
const[isHovered, setIsHovered] = useState(false)
The next step is to get the node of the element. If there's no node, return
const node = ref.current
The next step is to create a function that sets the hovered state to true when the mouse moves over the element (hovering)
const handleMouseEnter = () => setIsHovered(true)
Then, a function that sets the hovered state to false when the element is no longer hovered on. It receives the MouseEvent and uses event.relatedTarget to see where the mouse is.
const handleMouseLeave = (e: MouseEvent) => {
if(node && !node.contains(e.relatedTarget as Node)) {
setIsHovered(false)
}
}
To monitor the movement of the mouse on the app, event listeners are added to the node of the element.
node.addEventListeners("mouseenter", handleMouseEnter)
node.addEventListeners("mouseleave", handleMouseLeave)
Then, a function to clean up previous listeners when the app re-renders
return () => {
node.removeEventListeners("mouseenter", handleMouseEnter)
node.removeEventListeners("mouseleave", handleMouseLeave)
}
The final code looks like this:
import React, { useRef, useEffect, useState, Ref } from 'react'
export function useHover<T extends HTMLElement>(): [Ref<T>, boolean] {
// your code here
const ref = useRef<T>(null)
const[isHovered, setIsHovered] = useState(false);
useEffect(() => {
const node = ref.current;
if(!node) return;
const handleMouseEnter = () => setIsHovered(true)
const handleMouseLeave = (e: MouseEvent) => {
if(node && !node.contains(e.relatedTarget as Node)) {
setIsHovered(false)
}
}
node.addEventListener("mouseenter", handleMouseEnter)
node.addEventListener("mouseleave", handleMouseLeave)
return () => {
node.removeEventListener("mouseenter", handleMouseEnter)
node.removeEventListener("mouseleave", handleMouseLeave)
}
})
return [ref, isHovered]
}
// if you want to try your code on the right panel
// remember to export App() component like below
export function App() {
const [ref, isHovered] = useHover<HTMLDivElement>()
return <div ref={ref}>
{isHovered ? 'hovered': 'Not hovered'}
</div>
}
That's all folks!
Top comments (0)