0

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
1
  • Which data are you trying to reach from where? If you are trying to access the range state variable in the createPopup function, you can just directly access it by name. You can pass down the definition of the createPopup handler to your <GeoJSON /> component, but it is invoked in the scope of where it was defined.
    – Jacob K
    Commented Mar 5, 2022 at 19:58

1 Answer 1

1

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({});
    const [layer, setLayer] = useState({});

    const createPopup = () => {
        layer.on({
            mouseover: showCords,
        });
        layer.bindPopup(properties.NAME);
    }
    ...
}
2
  • Before asking your questions I tried something similar but I defined my states after my handler and it didn't work. If functions are hoisted anyways in javascript then why does the order of definition matter?
    – Tony
    Commented Mar 6, 2022 at 2:30
  • You're right, the order is non-important.
    – Sam
    Commented Sep 20, 2022 at 17:15

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