Search code examples
leafletreact-leaflet

Change background color of leaflet popup


I use leaflet and react. I need to change some popup styles, for example, a background color.

To open a window I use the code

marker.bindPopup(content,{className: 'custom-style'});

The main problem is that I get the styles from the backend and it will be different for each popup.

Because styles are different then I can't use this solution

.custom-style .leaflet-popup-content-wrapper,
.custom-style .leaflet-popup-tip {
    background-color: #f4913b;
}

How to properly assign custom styles to popup?


Solution

  • You can get the Popup HTML Element over marker.getPopup().getElement() and then add a style to it.

    It is important to add first the marker to the map and then bind the popup to the marker and open it directly! After adding the style you can close the popup again.

    var marker = L.marker(map.getCenter()).addTo(map).bindPopup("Test").openPopup();
    
    marker.getPopup().getElement().children[0].style.background = 'red'; // content
    marker.getPopup().getElement().children[1].children[0].style.background = 'red'; // tip
    
    marker.closePopup();
    

    Demo: https://plnkr.co/edit/ll8kjCocyWaueI8y