Back
Syntax
Study
Editor
Mode:
HTML
CSS
JavaScript
PHP
Reset
Run »
HTML / CSS / JS
import { useEffect, useRef } from 'react'; // Imaginary third-party map library // const map = new ThirdPartyMap(container, { zoom, center }); function MapWidget({ zoom, center }) { const containerRef = useRef(null); const mapRef = useRef(null); // Create the map once on mount useEffect(() => { mapRef.current = new window.ThirdPartyMap(containerRef.current, { zoom, center, }); return () => { mapRef.current.destroy(); // cleanup mapRef.current = null; }; }, []); // eslint-disable-line react-hooks/exhaustive-deps // Synchronise zoom whenever it changes useEffect(() => { if (mapRef.current) { mapRef.current.setZoom(zoom); } }, [zoom]); // Synchronise center whenever it changes useEffect(() => { if (mapRef.current) { mapRef.current.setCenter(center); } }, [center]); return <div ref={containerRef} style={{ width: '100%', height: 400 }} />; }
Result
Open