Reputation: 5968
In my component, i want to fire a fake onKeypress on a specific keycode, is it possible? i have this code:
class componentName extends Component {
fireKey = e => {
function makeKeyPressEvent(keyName, keyCode, charCode){
var event = new KeyboardEvent('keypress');
Object.defineProperties(event, {
charCode: {value: charCode},
keyCode: {value: keyCode},
keyIdentifier: {value: keyName},
which: {value: keyCode}
});
return event;
}
window.addEventListener('keypress', function(event){
console.log('key pressed!',
event.keyIdentifier, event.keyCode, event.charCode, event)
}, true);
var enterKeyEvent = makeKeyPressEvent('onClick', 39, 39);
window.dispatchEvent(enterKeyEvent);
}
render (
) {
return (
<div>
<button onClick={this.fireKey}> > </button>
</div>
)
}
}
or how can i manually change an event keyCode on onClick of button in react?
Upvotes: 0
Views: 2631
Reputation: 18
you can use this:-
class componentName extends Component {
fireKey = e => {
if(e.keyCode == 13){ //compare with your keyboard key
//your code here
}
}
render () {
return (
<div>
<button onKeyPress={this.fireKey}> > </button>
</div>
)
}
}
Upvotes: 1