Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to detect Click + [Shift, Ctrl, Alt] in reactjs click event?

Tags:

I want to do some other things when user Click+[Ctrl], but it seems that I could not detect if user press Ctrl when clicking.

I copy the event object infos below.

bubbles    :    false cancelBubble    :    false cancelable    :    false currentTarget    :    react defaultPrevented    :    false eventPhase    :    2 isTrusted    :    false path    :    Array[1] returnValue    :    true srcElement    :    react target    :    react timeStamp    :    5690056.695 type    :    "react-click" 

I can see the ctrlKey attribute in the arguments[0]-Proxy Object. But this object is unaccessable('Uncaught illegal access'):

[[Target]] : SyntheticMouseEvent _dispatchInstances:ReactDOMComponent _dispatchListeners:(e) _targetInst:ReactDOMComponent altKey:false bubbles:true button:0 buttons:0 cancelable:true clientX:275 clientY:315 ctrlKey:false 
like image 950
Jack Hu Avatar asked Aug 16 '16 12:08

Jack Hu


People also ask

How do you check if Shift key is pressed in react?

To detect Shift + Enter press in React onKeyPress event, we can check if shift+enter is pressed from the keypress event object. to set the onKeyPress prop of the input to the handleKeyPress function. We check if e. key is 'Enter' and e.

How do you trigger a button click event in react JS?

To add the click event in React using plain JavaScript, you need to use addEventListener() to assign the click event to an element. Create one <button> element as ref props so that it can be accessed to trigger the click event.


2 Answers

Your click handling function would have a format as such:

clickHandler: function (event, value) {     event.stopPropagation();     // In that case, event.ctrlKey does the trick.    if (event.ctrlKey) {         console.debug("Ctrl+click has just happened!");    } } 
like image 67
Christian Saboia Avatar answered Sep 21 '22 01:09

Christian Saboia


you can use this code below in your render() method

document.addEventListener('click', (e) => {   if (e.ctrlKey) {     console.log('With ctrl, do something...');   } }); 
like image 41
Kaveh Karami Avatar answered Sep 23 '22 01:09

Kaveh Karami