import React, { useEffect, useRef, useState } from "react"; import mapboxgl from "mapbox-gl"; import { useTheme } from "next-themes"; import Image from "next/image"; const LIGHT_STYLE = "mapbox://styles/mapbox/standard"; const DARK_STYLE = "mapbox://styles/mapbox/dark-v10"; const MapComponent: React.FC = () => { const { theme } = useTheme(); const mapContainerRef = useRef(null); const mapRef = useRef(null); const [mapLoaded, setMapLoaded] = useState(false); // Create map once useEffect(() => { if (mapRef.current) return; const map = new mapboxgl.Map({ accessToken: process.env.NEXT_PUBLIC_MAPBOX_TOKEN, container: mapContainerRef.current as HTMLElement, style: theme === "dark" ? DARK_STYLE : LIGHT_STYLE, center: [-122.3321, 47.6062], zoom: 10, }); map.on("load", () => { setMapLoaded(true); }); mapRef.current = map; return () => { map.remove(); mapRef.current = null; }; }, []); // Switch style without recreating the map useEffect(() => { if (!mapRef.current) return; mapRef.current.setStyle(theme === "dark" ? DARK_STYLE : LIGHT_STYLE); }, [theme]); return (
{!mapLoaded && ( Map )}
Icon
); }; export default MapComponent;