I'm trying to create component with Hook, but I'm faced with a strange problem.
I use mapbox-gl in my code. In order to init mapbox-gl, I have to wait until dom component is loaded. (useLayoutEffect or useEffect)
There is no problem in the initial display, but when I push the button(L72), the canvas which is created by mapbox-gl is unmounted with no console error.
I tried to move MyMap component outside the Tile component(L35-L45), then the above problem wasn't happened.
Am I using Hook incorrectly?
My sample full code is following.
[CodeSandbox]
This is an excerpt in Map.tsx:
export const Tile: React.FunctionComponent<PropsType> = ({
mapComponentLoaded,
trigger,
triggered
}) => {
const classes = useStyles({});
React.useLayoutEffect(() => { // or useEffect
// init mapbox-gl
mapComponentLoaded();
}, []); // run at once
// it doesn't works. if you clicked the button, the canvas under div#map would unmount.
const MyMap = (props: { triggered: boolean }) => (
<Paper className={classes.content}>
<div id="map" className={classes.map} />
<Typography>{props.triggered ? "fired" : "not fired"}</Typography>
</Paper>
);
return (
<div className={classes.root}>
<Grid container spacing={1} className={classes.root}>
<Grid item xs={12}>
<Button variant="contained" color="primary" onClick={() => trigger()}>
Add Boundary
</Button>
</Grid>
<Grid item xs={12} className={classes.map}>
<MyMap triggered={triggered} />
</Grid>
</Grid>
</div>
);
};
Thanks.