How to Handle the 'Onkeypress' Event in Reactjs

React onkeypress event to run a function

const handlePress = e => {
if(e.key === 'Enter') {
jump()
}
}

<button onKeyPress={handlePress}>Press Enter</button>

See key codes https://keycode.info/

Html elements div, h1, p, nav, ... don't receive events like keypress, focus, blur, ... by default. You can enable it specifying tabindex:

<div tabIndex={-1} onKeyPress={...}></div> // better to use <= 0

The above handleFunction runs if your cursor is over that element but if you want it to fire independent to cursors position, you should add eventlistener to window:

useEffect(() => {
window.addEventListener('keydown', e => {
if(e.key === 'Enter'){
console.log('You pressed Enter')
}
})
})


EDIT:

use keydown event otherwise arrow keys don't work

Handle onKeyPress event in ReactJS

You're setting location to be an empty string on every keypress, so Location state will be an empty string every time you call onChange.

So a fix for this is removing the setLocation("") in getWeatherInfo

React js call to a function when enter key is pressed

Try to move your onKeyDownHandler to separate function and just add if statement

  onKeyDownHandler = e => {
if (e.keyCode === 13) {
this.sendMessage();
}
};

render() {
... your other code
return (
<form
className="rcw-sender"
onKeyDown={this.onKeyDownHandler}
onSubmit={sendMessage}
>
{this.state.active && (
<Container>
<EmojiPicker />
</Container>
)}
<button className="rcw-send" onClick={activateEmoji}>
<img src={emojibutton} className="rcw-send-icon" alt="send" />
</button>
<button className="rcw-send" onClick={activateMenu}>
<img src={menubutton} className="rcw-send-icon" alt="send" />
</button>

<input
type="text"
className="rcw-new-message"
name="message"
placeholder={placeholder}
disabled={disabledInput}
autoFocus={autofocus}
autoComplete="off"
ref={this.input}
/>
<button type="submit" className="rcw-send">
<img src={send} className="rcw-send-icon" alt="send" />
</button>
</form>
);
}

How to combine 'onKeypress' and 'onClick' event in a single function

write a single function and call it on both onClick & onKeyPress..

function handleClickKeypress (event,url){

var code = event.keyCode || event.which;
if (code === 13) {
window.open(url);
}

else {
window.open(url);
}

}

Listen to keypress for document in reactjs

You should use keydown and not keypress.

Keypress (deprecated) is usually used only for keys that produce a character output as per the docs

Keypress (deprecated)

The keypress event is fired when a key is pressed down and that key normally produces a character value

Keydown

The keydown event is fired when a key is pressed down.



Related Topics



Leave a reply



Submit