'How to change style on Leaflet Map after props update?

A country is divided into 4 zones: North, East, South and West. There are many states in each zone. There is a dropdown in the App component to select the zone. It is passed down to the Map component as a prop. Which state belongs to which zone is present in the geoJSON file. The geoJSON file also contains the boundaries of each state drawn as a polygon.

What I want: I would like to color the states based on the zone selected. For example, when North zone is selected from the dropdown, the corresponding states are colored in Red. So, whenever there is an in props (selected zone), the corresponding states should be colored.

What I have done: I was able to color the states based on the zones using the code below.

Issue faced: On selecting a new zone from the dropdown, the map doesn't move. The map remains fixed at the position specified in setView. Or, if I create an alert, the alert doesn't go away on clicking 'OK'.

Map Component

componentDidMount() {
        this.setState({ selectedZone: this.props.selectedZone})
        var map = L.map("map").setView([17.3850, 78.4867], 10);
        L.tileLayer("https://{s}.tile.osm.org/{z}/{x}/{y}.png", {
            attribution: "OK",
            tileSize: 512,
            zoomOffset: -1
        }).addTo(map);

        L.geoJSON(statesData, {style: this.style}).addTo(map);    
    }

componentDidUpdate(nextProps) {
        if(this.state.selectedZone != nextProps.selectedZone){
            this.setState({ selectedZone: nextProps.selectedZone})
        }
        var container = L.DomUtil.get('map');
        if(container != null){
            container._leaflet_id = null;
        }
        var map = L.map("map").setView([17.3850, 78.4867], 10);
        L.tileLayer("https://{s}.tile.osm.org/{z}/{x}/{y}.png", {
            attribution: "OK",
            tileSize: 512,
            zoomOffset: -1
        }).addTo(map);

        L.geoJSON(statesData, {style: this.style}).addTo(map);    
    }

I feel that my mistake lies in the componentDidUpdate() function and that there is a better way to style the map with change in props.

Please let me know if anything is not clear or any extra information is required.

Many thanks!



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source