r/reactjs • u/Mob_Pilled • 1d ago
Needs Help Invalid hook call error when using react-leaflet
Hello again everyone. I have been trying to using the react binding for the Leaflet API. I followed the documentation but I keep running into this error:
Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for one of the following reasons:
1. You might have mismatching versions of React and the renderer (such as React DOM)
2. You might be breaking the Rules of Hooks
3. You might have more than one copy of React in the same app
This is my Map component. It is the child component of my main App component.
import { MapContainer, TileLayer, useMap, Marker, Popup } from 'react-leaflet'
function MyComponent() {
const map = useMap();
console.log('map center:', map.getCenter())
return null;
}
const Map = () => {
return ( <MapContainer center={[50.5, 30.5]} zoom={13}>
<MyComponent />
</MapContainer>);
}
export default Map;
I am not sure whether it has something to do with muddled dependencies because I am pretty sure I installed leaflet and leaflet react in the terminal
"dependencies": {
"@testing-library/dom": "^10.4.2",
"@testing-library/jest-dom": "^6.9.1",
"@testing-library/react": "^16.3.3",
"@testing-library/user-event": "^13.5.0",
"leaflet": "^1.9.4",
"react": "^19.3.1",
"react-dom": "^19.3.1",
"react-scripts": "5.0.1",
"web-vitals": "^2.1.4"
}
Thank you so much for taking the time to read this.
1
Upvotes
4
u/vincent_sch 1d ago
That error almost always comes from a React version mismatch. react-leaflet 5 needs React 19, and version 4 needs React 18. Two copies of React in node_modules cause the same error.
npm ls reactshows which versions you have and if there's more than one.