Search code examples
reactjsleafletreact-leaflet

react leaflet, pass marker's e.latlng property to formik


function Map({type="show"}) {
    function LocationMarker() {
        const [position, setPosition] = useState(null)
        const map = useMapEvent('click', (e) => {setPosition(e.latlng);console.log(e.latlng)});
        
          return position === null ? 
          null : (<Marker position={position}><Popup>You are here</Popup></Marker>)
        }
          return (
    <div className="App">
      <div id="map">
      <MapContainer center={[31.8123, 34.7770]} zoom={8}   onClick={console.log('hhh')}>
        <TileLayer attribution='&copy; <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors'
          url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png"
        />

 <LocationMarker/> 
      </MapContainer>
      </div>
    </div>
  )
}

hello, i want to build a functionality as follows: user clicks on the leaflet map-> which creates a marker on the clicked spot -> and pass the latlng of this spot to formik. my problem is that i dont know how to pass the latlng state outside the LocationMarker funtion. this is my first question here and i m pretty new to programming so I hope my question make sense and that you can help me with it.


Solution

  • You could either set the value directly in the component using formik using the setvalue function.

    const [field, meta, helpers] = useField(props.name);
    const { value } = meta;
    const { setValue } = helpers;
    

    Or if you want to set it in the parent component you can pass down a function that you will call when you set the position locally.

    function Map({type="show", onChange}) {
        function LocationMarker() {
            const [position, setPosition] = useState(null)
            const map = useMapEvent('click', (e) => {setPosition(e.latlng);console.log(e.latlng)});
            onChange(e.latlng);
              return position === null ? 
              null : (<Marker position={position}><Popup>You are here</Popup></Marker>)
            }