MarcoLe
MarcoLe

Reputation: 2509

React leaflet- how to add custom components with useLeaflet

I am trying to create an info panel for my leaflet map like so: leaflet-info-control. Furthermore I use react with react-leaflet. To access the global leaflet map object, react-leaflet provides the useLeaflet() hook.

The problem with my code is: I can see my component is rendered, but it is actually rendered behind the map. How can I add the div to/in front of the map?

Functional Comp.

import {useLeaflet} from "react-leaflet";
import React, {useEffect} from 'react';

function MapInfoControl({getColor}) {

    const leafletContext = useLeaflet();
    const grades = [95, 75, 50, 30, 25];

    useEffect(() => {
        console.log(leafletContext) // access the LeafletContext object.
    });

    return (
        <div className="legend">
            {
                grades.map((grade, i) => (
                        <React.Fragment key={i}>
                            <i className="legend-color-box" style={{background: getColor(grades[i])}}/>
                            {
                                grades[i] + (grades[i + 1] ? '&ndash;' + grades[i + 1] + '<br>' : '+')
                            }
                        </React.Fragment>
                    )
                )
            }
            )
            }
        </div>
    );
}

export default MapInfoControl;

Upvotes: 1

Views: 2356

Answers (1)

kboul
kboul

Reputation: 14570

You will do exactly the same thing as you would do without hooks with 3 main differences:

  1. create a functional component instead of a class based component
  2. use useEffect hook instead of componentDidMount
  3. use useLeaflet hook to access the map object instead of HOC withLeaflet

Here is demo with a live example.

I used the example provided by Leaflet's official docs to demonstrate it.

Upvotes: 4

Related Questions