When using divIcon in React Leaflet to render a custom Material UI marker with a background color prop, I noticed that the background style is not being applied correctly when the marker is displayed in Leaflet.
Below you can find the code for the project:
Codesandbox Link: https://codesandbox.io/p/sandbox/leaflet-mui-icon-forked-g23sc3?file=%2Fsrc%2FApp.js
Code snippet from Demo.js:
import * as React from "react";
import Button from "@mui/material/Button";
import LeafletMarker from "./LeafletMarker";
import { Marker, Popup, MapContainer, TileLayer } from "react-leaflet";
import ReactDOMServer from "react-dom/server";
import "leaflet/dist/leaflet.css";
import Box from "@mui/material/Box";
import L from "leaflet";
export default function Demo() {
return (
<div>
<LeafletMarker bgcolor={"green"} />
<MapContainer
center={[51.505, -0.09]}
zoom={13}
scrollWheelZoom={true}
style={{ width: "100%", height: "100vh" }}
>
<TileLayer
attribution='© <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors'
url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png"
/>
<Marker
draggable={true}
position={[51.505, -0.09]}
icon={L.divIcon({
className: "",
html: ReactDOMServer.renderToString(
<LeafletMarker bgcolor={"red"} />
),
})}
/>
</MapContainer>
</div>
);
}
Code snippet from LeafletMarker.js:
import Box from "@mui/material/Box";
import { createSvgIcon } from "@mui/material/utils";
const HomeIcon = createSvgIcon(
<path d="M10 20v-6h4v6h5v-8h3L12 3 2 12h3v8z" />,
"Home"
);
function LeafletMarker({ bgcolor }) {
return (
<Box
sx={{
width: "50px",
height: "50px",
borderRadius: 5,
bgcolor,
}}
>
<HomeIcon />
</Box>
);
}
export default LeafletMarker;
To show the background color, adding
style={{ backgroundColor: bgcolor }}
directly within the LeafletMarker component works. However, the preferred approach is to resolve this issue while using the sx property if possible.
EDIT: The example code has been corrected to include the original sx background color prop, which highlights the problem.