Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Popup always open in the marker

Is there any way the popup always stays open and does not need to click on it to open?

  • Expected behaviour
  • Actual behavior
like image 412
Titxo Avatar asked Nov 27 '22 23:11

Titxo


2 Answers

With the introduction of react-leaflet version 2 which brings breaking changes in regard of creating custom components, it is no longer supported to extend components via inheritance (refer this thread for a more details)

In fact React official documentation also recommends to use composition instead of inheritance:

At Facebook, we use React in thousands of components, and we haven’t found any use cases where we would recommend creating component inheritance hierarchies.

Props and composition give you all the flexibility you need to customize a component’s look and behavior in an explicit and safe way. Remember that components may accept arbitrary props, including primitive values, React elements, or functions.

The following example demonstrates how to extend marker component in order to keep popup open once the marker is displayed:

const MyMarker = props => {

  const initMarker = ref => {
    if (ref) {
      ref.leafletElement.openPopup()
    }
  }

  return <Marker ref={initMarker} {...props}/>
}

Explanation:

get access to native leaflet marker object (leafletElement) and open popup via Marker.openPopup method

Here is a demo

like image 106
Vadim Gremyachev Avatar answered Jan 22 '23 12:01

Vadim Gremyachev


What you can do is to make your own Marker class from the react-leaflet marker, and then call the leaflet function openPopup() on the leaflet object after it has been mounted.

// Create your own class, extending from the Marker class.
class ExtendedMarker extends Marker {
    componentDidMount() {
        // Call the Marker class componentDidMount (to make sure everything behaves as normal)
        super.componentDidMount();

       // Access the marker element and open the popup.
      this.leafletElement.openPopup();
    }
}

This will make the popup open once the component has been mounted, and will also behave like a normal popup afterwards, ie. on close/open.

I threw together this fiddle that shows the same code together with the basic example.

like image 36
Per Fröjd Avatar answered Jan 22 '23 11:01

Per Fröjd