Ad
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] ? '–' + grades[i + 1] + '<br>' : '+')
}
</React.Fragment>
)
)
}
)
}
</div>
);
}
export default MapInfoControl;
Ad
Answer
You will do exactly the same thing as you would do without hooks with 3 main differences:
- create a functional component instead of a class based component
- use
useEffect
hook instead ofcomponentDidMount
- use
useLeaflet
hook to access the map object instead of HOCwithLeaflet
Here is demo with a live example.
I used the example provided by Leaflet's official docs to demonstrate it.
Ad
source: stackoverflow.com
Related Questions
- → How to update data attribute on Ajax complete
- → October CMS - Radio Button Ajax Click Twice in a Row Causes Content to disappear
- → Octobercms Component Unique id (Twig & Javascript)
- → Passing a JS var from AJAX response to Twig
- → Laravel {!! Form::open() !!} doesn't work within AngularJS
- → DropzoneJS & Laravel - Output form validation errors
- → Import statement and Babel
- → Uncaught TypeError: Cannot read property '__SECRET_DOM_DO_NOT_USE_OR_YOU_WILL_BE_FIRED' of undefined
- → React-router: Passing props to children
- → ListView.DataSource looping data for React Native
- → Can't test submit handler in React component
- → React + Flux - How to avoid global variable
- → Webpack, React & Babel, not rendering DOM
Ad