Reputation: 1893
I am trying to update a marker's title (tooltip content when mouse hovers over...) dynamically, however that field stays stuck at what it was upon init.
Here is a simplified test case:
// @flow
import {
Box, Button
} from '@material-ui/core'
import React, { useState } from 'react';
import { Map, TileLayer, Marker } from 'react-leaflet'
import "leaflet/dist/leaflet.css"
import L from 'leaflet';
import icon from 'leaflet/dist/images/marker-icon.png';
let DefaultIcon = L.icon({ iconUrl: icon });
L.Marker.prototype.options.icon = DefaultIcon;
function Test(props) {
const [mstate, setMstate] = useState(false)
const [mlong, setMlong] = useState(13)
// let mlong = (mstate) ? 13.047 : 13
const flipMstate = () => {
setMstate(!mstate)
setMlong((mstate)? 13 : 13.047)
}
return (
<Box component='div' style={{ width: '80%', height: '80%', position: 'relative', }}>
<Button onClick={flipMstate} style={{ height: '10%' }} >
Change marker
</Button>
<Map
preferCanvas={true}
style={{ height: '90%' }}
center={[50.63, 13.047]}
zoom={13}
minZoom={3}
maxZoom={18}
>
<TileLayer
attribution='&copy <a href="http://osm.org/copyright">OpenStreetMap</a> contributors'
url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png?"
/>
<Marker
title={mlong}
position={[50.63, mlong]}
/>
</Map>
</Box>
)
}
export default Test
When clicking on the button, the marker moves, as it should. But if you hover on the marker, the tooltip will always display "13". Looking at the debugger shows that the "title" field gets updated correctly. If I modify the code to start in the other state, the tooltip display will always be 13.047
Am I doing anything wrong?
Upvotes: 0
Views: 1247
Reputation: 14600
Use react-leaflet's Tooltip
to achieve the desired behavior
<Marker position={[50.63, mlong]}>
<Tooltip direction="top" offset={[10, 0]}>
{mlong}
</Tooltip>
</Marker>
Upvotes: 2
Reputation: 1877
The settter of useState hook does not change your value immediately.
So when you are calling setMlong((mstate)? 13 : 13.047)
you are not using the updated mstate
value, but the old one.
Try to add useEffect
hook and handle dependend state there:
useEffect(() => {
setMlong((mstate)? 13 : 13.047)
}, [mstate]);
Or look at another solution in answer to this question:
useState set method not reflecting change immediately
Upvotes: 0