Detecting the click on the component react

Hello,
I am building a project where I need to detect the right click on a certain component but I cannot use onClick since I’m not setting an event listener on the div but on the component itself(I cannot access its contents, it’s from npm)

Is there a way to attach some kind of an event listener to it?

Thanks in advance

Please share the code you have written so far otherwise I’m forced to provide a vague unhelpful answer :wink: .

1 Like

Basically, it goes like this:

import { Map, Marker, GoogleApiWrapper } from 'google-maps-react';


<Map>
    <Marker />
<Map>

Now I need somehow to attach the event listener to Marker

What is stopping you from adding an onClick to the Marker component?

This lib right?

1 Like

Yes, that the lib I’m using. What is stopping me is that I cannot detect right click on it :sweat_smile:

I think it should be onContextMenu (or contextmenu in plain JS) but it doesn’t look like they support the event (Marker.js).

There might be some other way to do it, like a ref maybe, or using a listener higher up in the tree and then do some event delegation (both sounds potentially janky). Maybe look if a different lib supports the event.

What exactly is it you want to use the right-click for?


Edit: The react-google-maps lib has a onRightClick prop acording to the docs.

1 Like

Are you able to access the keycode from the event? I think you should be able to check for a right click that way if onRightClick doesn’t help.

Just to be clear, because the names are so badly chosen. The second library I linked to is not the same as the one you are using.

You are using google-maps-react, the second one is react-google-maps.

1 Like

Thank you, I’ve tried with the second lib as well and indeed, there is onRightClick prop but when I try to look for the target of the event, it returns undefined so I can’t pick its id or other attributes so I’m stuck again :grinning_face_with_smiling_eyes:

Edit: I figured out how to identify the marker I’m clicking on in the callback function, thank you so much for your time and effort!

1 Like