1
votes

I am trying to use MapBox-GL with React. I am trying to avoid using a wrapper.

I have sucessfully created the map using Class Components, but want to transform it to only using functions to take advantage of hooks. Displaying the map in a function works great:

const map = () => {
    new mapboxgl.Map({
    container: 'mapContainer',
    style: 'mapbox://styles/mapbox/light-v9',
    center: [7.32, 60.44],
    zoom: 6,
    })
};
const Map = () => {
    const style = {
        position: 'absolute',
        top: 0,
        bottom: 0,
        width: '100%',
        height: '100vh'
    };
    useEffect(()=>{
        map();

    });


    return (
        <Row type="flex" gutter="50">
            <Col xs={{ span: 18 }}>
                <div style={style} id="mapContainer" />
            </Col>
        </Row>
    );
}

However, I want to add controllers and do things with the map. I do this normally in ComponentDidMount().

I have tried adding map.addControl(geocoder); for example to the useEffect, as well as outside the Map function. I am only getting errors:

TypeError: map.addControl is not a function

1

1 Answers

2
votes

A counterpart to componentDidMount is useEffect with zero inputs.

map.addControl(geocoder) assumes that map is an instance of Map while it's a function and it doesn't return a value.

It should be:

const getMap = () => {
    return new mapboxgl.Map({ ... })
};

const Map = () => {
    useEffect(()=>{
        const map = getMap();
        map.addControl(geocoder);
    }, []);
    ...
};