The GeoJson component has a function onEachFeature that calls a handler, in this case it is createPopup.
<GeoJSON data={covidGeoJSON} onEachFeature={createPopup}></GeoJSON>
Within the handler createPopup how can I access states defined inside the CovidMap component?
import React, { useState } from 'react'
import { MapContainer, GeoJSON } from 'react-leaflet'
import 'leaflet/dist/leaflet.css'
CovidMap = ({ covidGeoJSON, styles }) => {
const showCords = (e) => {
console.log(e.latlng);
}
const createPopup = (state, layer) => {
layer.on({
mouseover: showCords,
});
layer.bindPopup(state.properties.NAME);
}
const [range, setRange] = useState([]);
return (
<div>
<MapContainer style={{ height: '90vh', width: '100vw' }} center={[39.162497380360634, -94.83672007881789]} zoom={5}>
<GeoJSON data={covidGeoJSON} onEachFeature={createPopup}></GeoJSON>
</MapContainer>
</div>
)
}
export default CovidMap
CodePudding user response:
You should be able to reference the state from createPopup
. Create & use state variables within CovidMap
using the useState
hook:
const CovidMap = () => {
...
const [properties, setProperties] = useState({}); // Defined BEFORE handler
const [layer, setLayer] = useState({}); // Defined BEFORE handler
const createPopup = () => {
layer.on({
mouseover: showCords,
});
layer.bindPopup(properties.NAME);
}
...
}