0

In a React + Typescript web application, I'd like to be able to show/hide the leaflet-draw "Draw polyline" button programmatically.

To perform this task, I acted on the EditControl's draw properties, as in this example (code sandbox at: https://codesandbox.io/s/leaflet-toggle-button-0hbr0?file=/src/MyMap.tsx:0-1257 )

import React, { useState } from "react";
import { MapContainer, TileLayer, FeatureGroup } from "react-leaflet";
import "leaflet/dist/leaflet.css";
import "leaflet-draw/dist/leaflet.draw.css";
import { EditControl } from "react-leaflet-draw";
import "leaflet-draw";

const MyMap = () => {
  const [showButton, setShowButton] = useState<boolean>(true);

  return (
    <>
      <button
        onClick={() => {
          setShowButton((oldValue) => !oldValue);
        }}
      >
        Toggle
      </button>
      <p>{"Show button: " + showButton}</p>
      <MapContainer
        center={[37.8189, -122.4786]}
        zoom={13}
        style={{ height: "300px" }}
      >
        <TileLayer
          attribution='&copy; <a href="http://osm.org/copyright">OpenStreetMap</a> contributors'
          url="http://{s}.tile.osm.org/{z}/{x}/{y}.png"
        />
        <FeatureGroup>
          <EditControl
            position="topright"
            draw={{
              rectangle: false,
              circle: false,
              circlemarker: false,
              polygon: false,
              marker: false,
              polyline: showButton
            }}
          />
        </FeatureGroup>
      </MapContainer>
    </>
  );
};

export default MyMap;

The button is originally displayed, and, after clicking the "Toggle" button, it correctly disappears.

Unfortunately, pressing the "Toggle" button again, it doesn't appear any more.

What is the proper way of achieving the correct behavior?

EDIT: according to https://github.com/Leaflet/Leaflet.draw#user-content-example-leafletdraw-config ,

You can change a draw handlers options after initialisation by using the setDrawingOptions method on the Leaflet.draw control.

Unfortunately, I don't manage to call that method, either.

Starnuto di topo
  • 3,215
  • 5
  • 32
  • 66

1 Answers1

1

I had a similar problem.

As a workaround, I'm setting draw options with an added key which is always different to bypass the prevProps VS props check. See below:

setDrawOptions({
  ...drawOptions,
  polyline: showButton
  bugWorkaround: Math.random(), // TODO remove when lib bug is fixed
});

That's really hacky but should get you going until it's fixed.

Junjou
  • 11
  • 1
  • 2