React: Remove focus from input element on escape key
Asked Answered
A

1

9

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)

Aciculate answered 15/1, 2021 at 16:38 Comment(0)
D
29

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

 onEscape(() => {
    descRef.current.blur();
 });
Dibble answered 15/1, 2021 at 16:41 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.