Sopon Kongnithigarn
Sopon Kongnithigarn

Reputation: 11

can't get latlng from react useref

Recently, I just started utilizing leftlet in my React ts project. I want to implement a draggable marker on the map. However, I cannot do anything with the return ref.

  const [position, setPosition] = React.useState(TEMP.center);
  const markerRef = React.useRef(null);

  const eventHandlers = React.useMemo(
    () => ({
      dragend() {
        const marker = markerRef.current;
        if (marker != null) {
          setPosition(marker.getLatLng());
        }
      },
    }),
    []
  );

and I get this error

Property 'getLatLng' does not exist on type 'never'.  TS2339

    50 |         const marker = markerRef.current;
    51 |         if (marker != null) {
  > 52 |           setPosition(marker.getLatLng());
       |                              ^
    53 |         }
    54 |       },
    55 |     }),

Upvotes: 1

Views: 480

Answers (1)

Mike Strother
Mike Strother

Reputation: 331

Change line 2 to:

    const markerRef = useRef<any>(null)

I ran into the same issue, this fixed it for me. Thanks to jnelson for the tip.

Upvotes: 1

Related Questions