I'm using react-leaflet to render a map. I created a component that has a map-property:
import * as React from 'react';
import { Map, FeatureCollection } from 'leaflet';
class Car extends React.Component {
state = {
map: Map,
collection: FeatureCollection
}
constructor(props) {
super(props);
this.state = {
map: props.map,
collection: props.collection
}
}
Now I try to use that component within my app:
import React, { useState } from 'react';
import { MapContainer, useMap } from 'react-leaflet';
import Car from './Car';
function Layout() {
return (
<div>
<MapContainer bounds={[[52.475,13.3], [52.477,13.5]]} zoom={12}>
<Car map={ useMap() }/>
</MapContainer>
</div>
)
}
export default Layout;
However I don't know how to provide the map from the MapContainer into my Car-component. Using the above code I get the following error:
TS2322: Type '{ map: string; }' is not assignable to type 'IntrinsicAttributes & IntrinsicClassAttributes & Readonly<{}> & Readonly<{ children?: ReactNode; }>'. Property 'map' does not exist on type 'IntrinsicAttributes & IntrinsicClassAttributes & Readonly<{}> & Readonly<{ children?: ReactNode; }>'.
useMap can only be used within a component that is itself a child/descendant of <MapContainer>.
https://react-leaflet.js.org/docs/api-map/#usemap
Hook providing the Leaflet Map instance in any descendant of a
MapContainer.
Your <Layout> component renders such <MapContainer>, but is not within one.
However, you can simply use useMap in the body of <Car>
That being said, it will probably not work if you keep your <Car> component class-based. You will probably have to either convert it to functional component, or use an older version of React Leaflet (2).