Code With Wolf

How to Change Marker Color with React-Leaflet

How to Change Marker Color with React-Leaflet

I wanted to change the color of the default markers on a leaflet map in a react app. I was using react-leaflet npm package and was struggling to find how to do this in the documentation.

First and foremost, don't waste your time trying to do this with CSS. You are going to have a bad time.

Those markers are images, and trying to pinpoint how they will be overlayed over your map layer and within the map container and applying a dynamic id to them to style them is not worth it.

Here is how I did it:

import { MapContainer, TileLayer, Marker, Popup } from "react-leaflet";
import * as L from "leaflet";
import { useState } from "react";

export default function App() {

    //  Create the Icon
  const LeafIcon = L.Icon.extend({
    options: {}

  const blueIcon = new LeafIcon({
    greenIcon = new LeafIcon({

    //  Use the state hook:
  const [icon, setIcon] = useState(blueIcon);

    // This function will change the state's icon:

  const changeIconColor = (icon) => {
    if (icon.options.iconUrl === greenIcon.options.iconUrl) {
      setIcon((current) => (current = blueIcon));
    } else {
      setIcon((current) => (current = greenIcon));
  return (
    <div className="App">
      <h1>React-Leaflet Map</h1>
      <h2>How to change a marker color</h2>

        style={{ height: "200px" }}
        center={[40.7608, -111.891]}
          attribution='&copy; <a href="">OpenStreetMap</a> contributors'
        <Marker position={[40.7608, -111.891]} icon={icon}>
            <h1>Salt lake City</h1>
            <button onClick={() => changeIconColor(icon)}>
              Change Marker Color

If you have the leaflet and react-leaflet npm modules installed, this should work for you. Click on the marker and you will see the popup with a "Change Marker Color" button. That should do the trick.

The idea here is that we are changing the Marker's image (it actually uses Google Map's pins here) and NOT trying to style Leaflet's default marker image. Trying to style that bad boy is going to give you a bad time.

© 2022 Code With Wolf