New to Typescript and need some clarification on how to resolve typing errors.
I'm setting the Mapbox container to mapDiv.current--it's giving me this error:
Type 'HTMLDivElement | null' is not assignable to type 'string | HTMLElement'.Type 'null' is not assignable to type 'string | HTMLElement'.ts(2322)
Though this can be fixed by doing mapDiv.current || ''. Is this the right way to resolve this type issue?
export const Map: FunctionComponent = () => {
const mapDiv = useRef<HTMLDivElement>(null);
let [map, setMap] = useState(null);
useEffect(() => {
const attachMap = (setMap: React.Dispatch<React.SetStateAction<any>>, mapDiv: React.RefObject<HTMLDivElement>) => {
const map = new mapboxgl.Map({
container: mapDiv.current, // ERROR
container: mapDiv.current || '', // NO ERROR
style: 'mapbox://styles/mapbox/outdoors-v11',
center: [-121.91390991210938, 40.316184625814095],
zoom: 10,
})
setMap(map);
}
!map && attachMap(setMap, mapDiv)
}, [map])
return (
<div className="Map" ref={mapDiv} />
)
}