Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Prevent bubbling/capturing when using custom react component on leaflet map

I am using React Leaflet and put my own custom component on top of it. To keep this on topic, I will just use examples to reduce fluff from other code.

The problem is that when double clicking, or dragging over the text in the input it interacts with the map and causes zoom or drag to happen on the map. I do not want that!

I am adding the proper methods to prevent bubbling/capturing, but I know react has synthetic events and those may work differently?? I have the styling to where it is placed over the map with position absolute with a high index. It shows up just fine so that is why I'm not using the MapControl class and extending it.

The input is nothing more than a basic input component:

import React from 'react'

export default function Search(){
  // stop bubbling/capturing not working
  const stopPropagation = (e) => {
    e.stopPropagation()
    e.preventDefault()
  }

  return (
  <div onClick={stopPropagation} onDoubleClick={stopPropagation}>
    <input onClick={stopPropagation} onDoubleClick={stopPropagation} type="text" />
  </div>
 )
}

The Map component, only thing here is to see I am using the Map and passing the Search comp as a child:

import React from 'react'
import { Map, TileLayer } from 'react-leaflet'

export default function Map() {
  return (
   <Map
    bounds={initBounds}
    maxZoom={30}
    onMoveend={handleMove}
    ref={mapEl}
   >
    <Search />
    <TileLayer 
        attribution='&amp;copy <a href="http://osm.org/copyright">OpenStreetMap</a> contributors'
        url='https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png'
    />
</Map>
 )
}
like image 810
Taylor Austin Avatar asked Oct 25 '25 04:10

Taylor Austin


1 Answers

You can use the leaflet disableClickPropagation method to disable bubbling/capturing.

import L from from 'leaflet'

// Inside your component where the input is

// ...
import { useRef, useEffect } from 'react'

const ref = useRef()

useEffect(() => {
        if(ref?.current){
            const disableClickPropagation = L?.DomEvent?.disableClickPropagation
            disableClickPropagation(ref.current)
        }

}, [])

return (
  <div ref={ref}>...</div>
)

like image 71
Taylor Austin Avatar answered Oct 26 '25 18:10

Taylor Austin