Search code examples
reactjsonclickonkeypress

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


I know this kind of questions has been asked before but here I have a problem where I have to write a single function that will handle 'onkeypress' when enter key is pressed and 'onclick' function on mouse click.

handleClick = (event, url) => {
window.open(url);
};

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

onClick={(event) =>
this.handleClickOnTraining(event)
}
onKeyPress={(event) =>
this.handleEnterKeyOnCards(event)
}

I want to combine these two into a single function like click or enterkey. How can I combine both?Can someone please help on this?


Solution

  • 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);
       }
    
    }