2

I'm using react-leaflet to render a GeoJSON feature collection that has points and linestrings: enter image description here

I was able to get the click and hover events on the actual features themselves to work just fine. But I'd like to be able to hover on a list item (related to the items on the map) and have the popup open. I've been sorting through the docs, github, and trying different things out. But it seems there's no way to do this. Or that I'll have to render my linestrings and points manually vs. using the <GeoJSON data=

My map works well with the click events:

return (
        <Map
            style={{
                height: '100%',
                width: '100%',
                margin: '0 auto'
            }}
            ref={(el) => {
                this.leafletMap = el;
            }}
            center={position}
            zoom={10}>
            <TileLayer url='https://api.mapbox.com/v4/mapbox.outdoors/{z}/{x}/{y}@2x.png?access_token=pk.eyJ1IjoiYWJlbnMwefwefEiOiJjajJ1bDRtMzcwMDssmMzJydHdvcjF6ODA5In0.xdZi4pmkhj1zb9Krr64CXw' attribution='&copy; <a href="https://www.mapbox.com/about/maps/">Mapbox</a>' />
            <GeoJSON data={locations} onEachFeature={this.onEachFeature} />{' '}
        </Map>
    );

onEachFeature works as it should

onEachFeature = (feature, layer) => {
        console.log('onEachFeature fired: ');
        layer.on({
            mouseover: (e) => this.MouseOverFeature(e, feature),
            mouseout: (e) => this.MouseOutFeature(e, feature)

        });
    };

But I don't see how to call the layer.bindPopup without using onEachFeature. How does one change call these methods using prop values? I'd like to let people hover on a list item and have it toggle the popups.

0

1 Answer 1

5

Add the following to:

<GeoJSON data={locations} onEachFeature={onEachFeature} />:

onEachFeature(feature, layer) {
  const popupOptions = {
    minWidth: 250,
    maxWidth: 500,
    className: "popup-classname"
  };

  const popupContentNode = <MyReactComponent />;
  const popupContentHtml = ReactDOMServer.renderToString(popupContentNode);

  layer.bindPopup(popupContentHtml, popupOptions);
}

You'll also need this for adding rendered React components to the popup:

import ReactDOMServer from "react-dom/server";

Note you'll have to make your own event binding if you want to use reactive components in the popup.

1
  • hey, I tried to create a form within the popup (as a seperate react component) but it was breaking the handleSubmit, like it wouldnt preventDefault etc. how would i attach the event binding?
    – Wboy
    Commented Feb 16, 2022 at 10:15

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.