Search code examples
reactjsreact-hooksfocusrefuse-ref

React: Remove focus from input element on escape key


I have an input tag, when I press the escape key, I want the focus on the input element to go away, meaning there is no longer a text cursor or any focus styling(when the user types, their input will not go into the input tag).

The code below is my attempt at implementing the functionality described above, but it does not work as intended. I would like to get this code to work as intended.

import React, { useRef } from 'react';

const onEscape = function (action) {
    window && window.addEventListener('keydown', (e) => {
        if (e.key === "Escape") {
            action();
        };
    });
};

const MyComponent = () => {

    ...

    const descRef = useRef();
    onEscape(() => {
        descRef.blur();
    });

    return (
        <div>                
            <input
                ref={descRef}
                ...
            />
        </div>
   );
};

I have tested that onEscape function and it works when other actions are passed to it(when the user presses the escape key, it executes whatever function has been passed to the onEscape function)


Solution

  • Just from glancing at your code all you need is to add the current property to the ref Try this

     onEscape(() => {
        descRef.current.blur();
     });