I'm trying to use react-map-gl library to make a route of public transportation. I've found an example code to make a route that goes like this (Map.js):
import MapGL, { CanvasOverlay } from 'react-map-gl';
import React, { useState, PureComponent } from 'react';
import 'mapbox-gl/dist/mapbox-gl.css';
import starterRoutes from '../data/starterRoutes';
class PolylineOverlay extends PureComponent {
_redraw({ width, height, ctx, isDragging, project, unproject }) {
const { points, color = '#FF482D', lineWidth = 3, renderWhileDragging = true } = this.props;
ctx.clearRect(0, 0, width, height);
ctx.globalCompositeOperation = 'lighter';
if ((renderWhileDragging || !isDragging) && points) {
ctx.lineWidth = lineWidth;
ctx.strokeStyle = color;
ctx.beginPath();
points.forEach((point) => {
const pixel = project([point[0], point[1]]);
ctx.lineTo(pixel[0], pixel[1]);
});
ctx.stroke();
}
}
render() {
return <CanvasOverlay redraw={this._redraw.bind(this)} />;
}
}
// main map component is here
const Map = () => {
const [viewport, setViewPort] = useState({
width: '100%',
height: '100%',
latitude: 38.889726473242526,
longitude: -77.00320124234425,
zoom: 12.721197192553936,
});
const _onViewportChange = (viewport) => setViewPort({ ...viewport, transitionDuration: 20 });
return (
<MapGL {...viewport} mapboxApiAccessToken='MAPBOX_API_KEY' mapStyle='mapbox://styles/mapbox/streets-v9' onViewportChange={_onViewportChange}>
{starterRoutes.map((route) => (
<PolylineOverlay points={route.direction0LatLongs} key={route.RouteID} />
))}
</MapGL>
);
};
export default Map;
Then I try to use it in App.js:
import './App.css';
import 'mapbox-gl/dist/mapbox-gl.css';
import React from 'react';
import MapOverlay from './Components/Map.js';
function App() {
return <MapOverlay />;
}
export default App;
And I got the error mesagge:
Cannot update a component (Map) while rendering a different component (InteractiveMap).
Then I've tried to use React.lazy to import the Map component:
import './App.css';
import 'mapbox-gl/dist/mapbox-gl.css';
import React, { lazy, Suspense } from 'react';
const MapWithReactLazy = lazy(() => import('./Components/Map'));
function App() {
return (
<Suspense>
<MapWithReactLazy />
</Suspense>
);
}
export default App;
And still got the same error. How can I resolve this? Thanks
I don't know how to resolve the error, I hope someone can help me out to resolve the error.