The styling of divIcons in React Leaflet Material UI is not applied as expected

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

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.

Answer №1

If my understanding is correct that you are requesting a change in the background color of the marker container, I have found a solution:

const CustomMarker = ({ backgroundColor }) => {
  return (
    <Container
      style={{
        backgroundColor: backgroundColor,
        width: "50px",
        height: "50px",
        borderRadius: 5,
      }}
    >
      <Icon />
    </Container>
  );
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Timing of Bindings in AngularJS

In my setup, I have a controller that calls a service to retrieve a list of categories: $scope.enquiryCategories = CategoryServices.listCategories(); The service then fetches this data from an external API: listCategories: function () { return $http({ ...

Steps for creating a table with a filter similar to the one shown in the image below

I am unsure how to create two sub-blocks within the Business A Chaud column and Potential Business Column. Thank you! I managed to create a table with input, but I'm struggling to replicate the PUSH & CtoC Column format in both Business A Chaud and ...

Tips for customizing the color of mat-select placeholder text?

I've been attempting to modify the color of a mat-select placeholder. It functions properly when using 'background-color' but not when using 'color'. Below is my CSS code: /deep/ .mat-select-placeholder { color: red; } .mat-s ...

Instantaneous data refresh using Firebase Cloud Functions

Currently, I am working on developing a chat feature in React using Firebase cloud functions. However, I am facing an issue where I do not receive updates when a user sends a message. Below is the code snippet that I have been working with: const app = a ...

Confusing Vaadin Component Styling Dilemma

I've been struggling to access the individual parts of elements that require navigating through the shadow DOM. I've been following a guide for assistance: https://github.com/vaadin/vaadin-themable-mixin/wiki/1.-Style-Scopes When I add this code ...

Sorting prices in descending order using Expedia API

Is there a way to arrange prices in descending order using the response.hotelList[i].lowRate? The provided code is as follows: success: function (response) { var bil = 1; var hotel_size = response.hotelList.length; $('#listD ...

jQuery unable to locate elements or update class following AJAX response

My jQuery.on() event functions are working great when bound to specific elements like "a.my-link". However, I have one function that is bound to the document or body and then traverses multiple elements with the same class attribute. Certain lines in this ...

What is the mechanism through which a flexbox enlarges to accommodate its overflowing child elements?

I am working with a flexbox layout. Here is the HTML code structure: <div class="grid"> <div class="row"> <div class="column">Content</div> <div class="column">Content2</div> <div class="column">Con ...

JavaScript events for scrolling horizontally and vertically across multiple browsers

Is there a way to capture mousewheel and touchpad events, including on Mac, using JavaScript? Ideally, I want to get deltaX and deltaY values for both horizontal and vertical movements. I came across a website - - that appears to handle touchpad events ho ...

What are some ways that next.js Link can prevent unnecessary server requests?

Following that, there is a need to establish connections between these pages. While an HTML tag could be used for this purpose, it would result in server requests and page refreshes, which is not the desired outcome. import Link from 'next/link&apos ...

What is the best way to switch between different styles for each paragraph using CSS?

I attempted to use the :nth-of-type selector, but I am uncertain if it is feasible or if it accomplishes what I desire. My goal is to create an alternating style: two paragraphs aligned on the left, followed by two on the right, and so forth, regardless of ...

Crafting an iframe that dynamically adjusts with Tailwind CSS

I'm having trouble ensuring that an iframe fits properly within a div while using tailwind CSS. I'm struggling to make the iframe responsive, no matter what class I try. Can anyone suggest a class that would help me achieve responsiveness for an ...

Accept forward slashes in route parameters on React

I have a similar router setup: <Route path="/blog/:date/:folder" render={(props: any) => <Home /> It functions well with URLs like this: http://localhost/blog/2017-05-20/test But, when :folder includes slashes (subdirectories), I want to ca ...

Position the text to the right of the div or image and allow

My attempt to align the lorem ipsum sample text next to the image and div container by setting the float to right has not been successful. The text still remains below the image. Click here for visual reference Appreciate any help in advance. #outer { ...

Using Material UI to showcase an array of objects in a sleek and user-friendly table interface

https://i.stack.imgur.com/elpEs.png In the interface I am working with, I showcase a set of values. One key aspect is the "deduction" field which can contain one, two, three, or multiple values in an array. Most lines in the table feature a single Deducti ...

What could be causing the whitespace around this element when using SASS from Refills / Bourbon.io?

I've recently started using the impressive SASS framework, Boubon.io created by the talented team at thoughtbot. As I experiment with their supplied templates (known as Refills), I'm finding that Bourbon.io serves as a versatile alternative to po ...

Send an identifier to the following page upon selecting a hyperlink in AngularJS

I am currently working on a project that involves displaying a list of places and allowing users to click on a place to view more details on another page. I would like some guidance on how to implement this feature. Here is the HTML code for Page1: <l ...

Removing the arrow icon preceding an image in a new line when dealing with dynamic data

My Angular project renders dynamic content that includes the following HTML structure: <div class="complted" *ngFor="let step of letStep1to7; let i = index; let first = first"> <table> <td class="steps" ...

Combining Multiple 3D JSON Objects in JavaScript [or jQuery]

Looking to combine multiple JSON objects into one? I have a code snippet that you can use! Here is the code: http://jsfiddle.net/5Uz27/ The issue with this code is that it only merges objects on the first level, causing deeper levels to be overwritten. T ...

The Protractor option is nowhere to be found on the Run Configuration popup window in Eclipse

Issue with Protractor in Eclipse: Unable to locate Protractor option on Run Configuration popup. Despite following the steps outlined in http://www.protractortest.org/#/ and this guide on configuring Protractor with Eclipse (specifically the 2 Answer step ...