4

I have overridden the onClick function of anchor() tag in ReactJs to show loading.

const child: ReactElement = Children.only(children);

const childProps = {};

childProps['onClick'] = (event) => {

    if (childProps.href && child.props.target !== '_blank') {
        props.showSpinner(true);
    }

    let onClick = child.props.onClick;
    onClick && onClick();
};

return React.cloneElement(child, childProps);

But the problem is that if the user clicks on anchor(<a>) with shift and command keypress, then the user switches to the new tab but loading started showing.

So I added the following condition to show loading.

if (!event.shiftKey && childProps.href && child.props.target !== '_blank') {
   props.showSpinner(true);
}

This code handled the Shift key press but I have to handle command keypress also. I searched through many posts, they showing solution for alt, shift, and ctl keypress but not command keypress.

Ravi Sevta
  • 2,817
  • 21
  • 37

3 Answers3

3

You can check value of event.metaKey inside onClick of a button.

    <button
      onClick={e => {
        console.log("CLICKED", e.metaKey);
      }}
    >
      Press
    </button>

In above example, You will get value of e.metaKey as true if command is pressed.

  • 2
    for docs about event.metaKey : [https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/metaKey](https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/metaKey) – Ravi Sevta Oct 17 '19 at 08:35
0

As far as I understand when we are working with React, window object is not available directly, have you tried with componentDidMount function

Soheb
  • 788
  • 6
  • 11
0

I wrote a library that uses mouse modifiers to select things similar to how you can on operating systems!

Anyways, there is an example of detecting if the user is on Mac os and handling the meta key in the source code. Check out the pivot reducer.

https://github.com/ssteuteville/react-selection-hooks

rocktheartsm4l
  • 2,129
  • 23
  • 38