Dynamically change the background color of the TileLayer attribution

48 Views Asked by At

I have created a component that contains the map and changes the map for dark or light mode. How can I dynamically change the color of the attribution? There's any props or style key that i can use ?

Here is the component:

import {url, attribution, subdomains} from ./utils;

const MapComponent = () => {
    const { theme } = useTheme()

    return (
        <div className='rounded-lg border overflow-hidden'>
            <MapContainer
                zoom={6}
                minZoom={4}
                maxZoom={14}
            >
                <TileLayer
                    url={theme == 'dark' ? url.dark : url.light}
                    attribution={attribution}
                    subdomains={subdomains}
                />
            </MapContainer>
        </div>
    )
}

export default MapComponent;

I already try to apply different class or style on the TileLayer component and MapContainer but doesn't work because apply the style to the parents div of the one that contains the attribution.

1

There are 1 best solutions below

0
Ian A On

You could surround your map in a container (e.g. a div), give a CSS class to that which indicates the current theme (this will update as the theme changes), and then add a CSS selector to style the attribution element.

Component

You will need to add something to keep track of the theme and handle changing of the theme:

const [theme, setTheme] = useState('light');

const changeTheme = () => {
  setTheme((oldTheme) => (oldTheme === 'light' ? 'dark' : 'light'));
};

Then add a container surround the MapContainer whose className is the current theme:

<div className={theme === 'dark' ? 'map-dark' : 'map-light'}>
  <MapContainer
    center={[52.4498, -1.6]}
    zoom={12}
    scrollWheelZoom={false}
    ref={setMap}
  >
    <TileLayer
      attribution='&copy; <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors'
      url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png"
    />
  </MapContainer>
</div>

CSS

.map-dark .leaflet-container .leaflet-control-attribution {
  background: #000000;
}

Then when your theme changes, the attribution background should change along with it. There's a StackBlitz example demonstrating this. Use the "Toggle Theme" button to switch between light and dark themes.