J
J
JastaFly2020-09-10 21:23:24
React
JastaFly, 2020-09-10 21:23:24

Enter event handler in React?

Good day to all! It was necessary to hang up an event handler for pressing the Enter key. Along the way, I ran into a problem: the element on which I hung the event handler at the time of creation does not yet exist. In total, everything was done through setTimeout:

function Typing_message() {
    let messageField = React.createRef();
    setTimeout(function () {
        messageField.current.addEventListener('keydown', function (keyPress) {
            if (keyPress.keyCode == 13) {
                console.log('Enter press');
            }
        })
    }, 1000);
    return (
        <div className={style.typing}>
            <div className={style.typing__icon}>
               
            </div>
            <textarea ref={messageField} placeholder="Type your message..." name="" className={style.typing__field}></textarea>
            <div className={style.typing__icon}>
               
            </div>
            <div className={style.typing__icon}>
    
            </div>
        </div>
    );
}

But this is some kind of horseradish game on the balalaika. Is there any more elegant solution?!??

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alexander Cheremkhin, 2020-09-10
@JastaFly

Why are you making life difficult for yourself? Here is a typical solution

const onKeyDown = e =>{
// обработайте нажатие клавиши. 
}
return (
    <textarea onKeyDown={onKeyDown} .../>
)

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question