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) => {
const mouseEnter = (e) => {
const mouseLeave = (e) => {
return (
<div className="input-div"
Hover and press a key to see if it works.
{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 .