Give an Element Focus when Hovering Over it in React

Posted in Programming

Let's say you want to implement a React component that gives a DOM element focus when hovering your cursor over it, perhaps so that the component will accept keyboard input. There may be multiple ways to do this, but I like to use the useRef hook to focus when a mouseEnter event is received, and blur when a mouseLeave event is received.

Here is an example of a React component that shows which keys are pressed when the cursor is over it.

import {useRef, useState} from 'react';
const InputDiv = () => {
const inputDiv = useRef();
const [key, setKey] = useState();
const keyDown = (e) => {
setKey(e.key);
}
const mouseEnter = (e) => {
inputDiv.current.focus();
}
const mouseLeave = (e) => {
setKey(null);
inputDiv.current.blur();
}
return (
<>
<div className="input-div"
ref={inputDiv}
onMouseEnter={mouseEnter}
onMouseLeave={mouseLeave}
onKeyDown={keyDown}
tabIndex={-1}>
Hover and press a key to see if it works.
</div>
{key && <p className="result">You pressed {key}</p>}
</>
)
};

We create an inputDiv reference with the useRef hook, and then pass that as the ref property of the div. This allows us to access the focus() and blur() functions on the div elsewhere in the component.

When the mouse enters, we focus() the div. When the mouse leaves, we blur() it.

You may have noticed the use of tabIndex={-1}. This is necessary to indicate that a div can gain focus (normally a div cannot gain focus). Setting the tab index to -1 indicates that it can gain focus, but it will not be reachable by keyboard navigation. Set it to 0 if you want to be able to reach it by keyboard.

You can see it in action at Codepen.io .