I am following leafletjs's interactive choropleth map example and I am trying to add interaction by using the GeoJson object's resetStyle method and the Map object's fitBounds method. In leaflet, these methods are called via a reference to the respective objects:
var map = L.map('map');
function zoomToFeature(e) {
map.fitBounds(e.target.getBounds());
}
var geojson;
// ... our listeners
geojson = L.geoJson(...);
function resetHighlight(e) {
geojson.resetStyle(e.target);
}
How can I access these methods in react-leaflet? The methods don't exist in the objects returned from user interaction. I also tried exporting them from react-leaflet but that doesn't work either.
Here is my jsfiddle.
I know this same question was asked a month ago, but the solution, to access this.refs.geojson.leafletElement.resetStyle(e.target)
, doesn't work anymore because refs
is not a property of e.target
and this
just refers to e.target
.
One way would be to attach a 'ref' attribute to the GeoJSON component, and pass through your component to your event handlers.
JSFiddle: https://jsfiddle.net/thbh99nu/2/
<GeoJson data={statesData}
style={style}
onEachFeature={onEachFeature.bind(null, this)}
ref="geojson" />
// reset default style on mouseOut
function resetHighlight (component, e) {
// Just to show the ref is there during the event, i'm not sure how to specifically use it with your library
console.log(component.refs.geojson);
// geojsonresetStyle(e.target);
// how to encapsulate GeoJson component/object?
}
// `component` is now the first argument, since it's passed through the Function.bind method, we'll need to pass it through here to the relevant handlers
function onEachFeature (component, feature, layer) {
layer.on({
mouseover: highlightFeature,
mouseout: resetHighlight.bind(null, component),
click: zoomToFeature
});
}