pomipiwimo
pomipiwimo

Reputation: 89

React Leaflet Material UI divIcon not styled

In React Leaflet, I am trying to use divIcon to render a custom Material UI marker that takes in a background color prop. However, when the marker is used in leaflet, the background style is not applied.

Below is the code for the project:

Codesandbox: https://codesandbox.io/p/sandbox/leaflet-mui-icon-forked-g23sc3?file=%2Fsrc%2FApp.js

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='&copy; <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>
  );
}

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;

I have been able to get the background color to show by adding style={{ backgroundColor: bgcolor }} in LeafletMarker however I would prefer to get it working using the sx property if possible.

EDIT: Corrected the example code as the it did not include the original sx background color prop that showcases the issue.

Upvotes: 0

Views: 239

Answers (1)

ckesplin
ckesplin

Reputation: 1793

If I understand correctly that you want the background of the marker container to change colors, I got it to work with the following:

function LeafletMarker({ bgcolor }) {
  return (
    <Box
      sx={{
        backgroundColor: bgcolor,
        width: "50px",
        height: "50px",
        borderRadius: 5,
      }}
    >
      <HomeIcon />
    </Box>
  );
}

Upvotes: 0

Related Questions