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

Applying CSS styles to my container through a button click event

Currently, I am attempting to apply a padding-top to my container when a button is clicked. Unfortunately, the padding-top is not being added as expected. $('#login').on('click', function(){ $('#loginform1').css('padd ...

How can a REST API prompt a user to set a password upon their initial login?

Running into a scenario with my NodeJS REST API and React app. When a user logs in for the first time, I want to direct them to a page in React where they can set a new password before proceeding. How do I go about achieving this? What should the API retur ...

Welcome to the awe-inspiring universe of Typescript, where the harmonious combination of

I have a question that may seem basic, but I need some guidance. So I have this element in my HTML template: <a href=# data-bind="click: $parent.test">«</a> And in my Typescript file, I have the following code: public test() { alert( ...

Utilizing React hooks to dynamically toggle a class within a component

While similar questions have been raised previously, none seem to address my specific issue. Most references involve class components that do not align exactly with what I am attempting to achieve. My goal is to toggle two components on and off with a simp ...

There was a parsing error due to an unexpected token, and we were expecting a comma instead

Below is the code snippet written in react js: class Posts extends Component { render() { return ( {console.log('test')} ); } } When I executed this code, an error occurred stating: Parsing error: Unexpected token, expected " ...

Utilizing ObjectId for filtering and calculating overall cost in react.js: a guide

The table should only render once for Wade Ivan, with a total of 180 instead of 680. Seeking assistance to optimize my search class component. Currently, when searching for clients by their names based on ObjectId(clientdetails._id), the rendering returns ...

Compilation failure resulting from core UI build in React js

I have recently transitioned my domain to React Js and am in the process of learning. I have been working on creating an admin panel using Core UI Reactjs components, however I keep encountering an error that says "This error occurred during the build ti ...

The CSS linear gradients rainbow wheel is missing a few sections, only displaying part of its 12

I've almost got everything working, but I'm facing a challenge in displaying all 12 sections of the rainbow wheel. I know it's probably something very simple (Occam's razor). I've been following this amazing tutorial on CSS linear ...

The epoch time indicates a 12-hour difference

I keep encountering an error with the time showing as 12:00 P.M. When I receive a response in epoch time format 1454092200000, it corresponds to 1/30/2016, 12:00:00 AM GMT+5:30 $scope.shipmentDate = moment(1454092200000).format("YYYY/MM/DD hh:mm"); The ...

Utilizing one JavaScript file and consistent classes for multiple modals

Is it possible to have multiple modals using the same JS file, classes, and IDs? I created this code: <button id='myBtn'>Order/Discount</button> <div id='myModal' class='modal'> <div clas ...

The specified type `Observable<Pet>&Observable<HttpResponse<Pet>>&Observable<HttpEvent<Pet>>` is not compatible with `Observable<HttpResponse<Pet>>`

I'm currently attempting to integrate the Angular code generated by openapi-generator with the JHipster CRUD views. While working on customizing them for the Pet entity, I encountered the following error: "Argument of type 'Observable & ...

Placing the error message for validation in its appropriate position

My login form has a layout that looks like this: https://i.stack.imgur.com/i7rCj.png If I enter incorrect information, it displays like this: https://i.stack.imgur.com/ItNJn.png The issue is that when the error message appears, it causes the login form ...

What is the best way to direct the next input focus when pressing Enter in ReactJS?

I have a TextField component from MaterialUI in my ReactJS project. I want to set focus on the next field when the enter key is pressed on a Google Keyboard. Can anyone guide me on how to achieve this functionality? ...

Having difficulty completing the text field and submitting it automatically

My goal is to automatically fill in the "Reason for Access" text box with the word "TEST" using Tampermonkey. I am new to using Tampermonkey and UserScript, so I appreciate your patience. Currently, I am facing an issue where the "Reason for Access" field ...

Instructions on creating a Superfish menu with a vertical layout in the first level and a horizontal layout in the second level

Currently, I am using the Superfish menu in Drupal7 and have designed my first item level to be vertical. However, I now want to style my second item level horizontally. I have tried various CSS approaches and added some class names via jQuery like $(&apo ...

Guidelines for establishing authentic headers on a SignalR connection

Can headers be set on the SignalR connection directly? I am aware of setting query string parameters but it is not secure enough for my specific scenario. var conn = ($ as any).hubConnection(); conn.url = URL; conn.qs = { "token": SECRET_KEY }; conn ...

unable to maximize the iframe to full screen

I am currently implementing a Material UI Card in my component to display a YouTube video using an iframe. Everything seems to be working well, but I'm facing an issue with making the video fullscreen as it keeps saying fullscreen is unavailable. Che ...

The second JSP page fails to load following an AJAX POST request

The following code snippet is found in page1.jsp. $.ajax({ type: "post", url: "page2.jsp", data: newdata, success:function(msg){ return msg; } ...

analyzing strings by comparing their characters to another string

In a scenario where I have two strings; let's call them string a="a-b-c" and string b="a-b". I am looking to determine whether every letter in string b is present within string a. ...

What is the best way to set up a session using jQuery?

I've been troubleshooting my code and I can't seem to figure out why the jquery.session.js file isn't working. Can someone help me find a solution? $.session.set('rmng_time', remaining_seconds); alert("j session "+$.sessi ...