'Nextjs react-leaflet Error: Map container is already initialized
I'm using react-leaflet in a nextjs project, after dynamically loading the map component I'm getting this error Error: Map container is already initialized. I was not getting this error in plain create-react-app project, but only when we migrated the code to nextjs.
// Location.js
import { MapContainer, TileLayer, Marker, Popup, useMap } from "react-leaflet";
function ChangeMapView({ coords, zoom }) {
const map = useMap();
map.setView(coords, zoom);
return null;
}
function Location(props) {
const position = [props.lat, props.long];
return (
<MapContainer center={position} zoom={props.placeType === "city" ? 10 : 5}>
<TileLayer
attribution='© <a href="http://osm.org/copyright">OpenStreetMap</a> contributors'
url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png"
/>
<ChangeMapView
coords={position}
zoom={props.placeType === "city" ? 10 : 5}
/>
<Marker position={position}>
<Popup>{props.city}</Popup>
</Marker>
</MapContainer>
);
}
export default Location;
Let me know if you might need more information regarding code.
const Location = dynamic(() => import("./Location"), {
ssr: false,
});
class Calculator extends React.Component {
// some code
render() {
return (
// more code
<section className="location">
<h1>Location </h1>
{this.state.selectedCity.city ? (
<Location
lat={
this.props.router.query.zip_code
? this.state.selectedCity.latitude
: this.state.selectedCity.latitude + 0.01
}
long={
this.props.router.query.zip_code
? this.state.selectedCity.longitude
: this.state.selectedCity.longitude + 0.01
}
city={
this.props.router.query.zip_code
? this.state.selectedCity.city
: this.state.stateName
}
placeType={this.props.router.query.zip_code ? "city" : "state"}
/>
) : (
""
)}
</section>
);
}
}
export default withRouter(Calculator);
(Edit): This Error doesn't come up once I downgraded to react v17. So it seems like this issue only affects react v18
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
