Search code examples
javascriptreactjstypescriptleafletreact-leaflet

How to stop a click propagation for custom react components that are child to MapContainer


I`ve created a custom control react component for map like that:

export const MapZoom = () => {
    const map = useMap()
    const handleButtonClick = () => {
        map.zoomIn()
    }

    return (
        <IconButton
            aria-label="clear all figures"
            bgColor="#ffffffe2"
            color="balck"
            onClick={handleButtonClick}
            icon={<FaPlus />}
        />
    )
}

I added that component in MapContainer like that:

<MapContainer
            center={[51.509865, -0.118092]}
            zoom={10}
            minZoom={2}
            maxBounds={maxBounds}
            maxBoundsViscosity={1.0}
            doubleClickZoom={false}
            style={{
                height: '100vh',
                width: '100vw'
            }}
        >
            <TileLayer url="https://tile.openstreetmap.org/{z}/{x}/{y}.png" />

            <MapZoom/>

</MapContainer>

If i add to MapZoom that styles: position absolute, zIndex 999, this component will display over the map, but the main problem if i click at my component, the map will handle this click also. That make some problems like this: enter image description here When i use my slider, map reads click and set a circle in wrong way.

Ive tried to stop click propagation, so map wouldnt handle that click, also i used react-leaflet-custom-control that worked greate but i couldn`t place my component in center :( So i want to find a solution for this, not a kludge.


Solution

  • for me , to simply avoid this case, i set a particular attribute to the button. So if it's you who had create the IconButton component, just add a prop like:

    <IconButton
                aria-label="clear all figures"
                id="btnZoom"
                bgColor="#ffffffe2"
                color="balck"
                onClick={handleButtonClick}
                icon={<FaPlus />}
            />
    

    Then you should test this id value in your event action like :

    const handleButtonClick = (e) => {
            if(e.target.id === "btnZoom"){
                map.zoomIn()
            }
        }