Reputation: 411
I have a map of a country (SVG) and I want to highlight a province/state when I hover over it, changing its color/fill. I implemented this but the problem is that onMouseEnter highlights the entire map not just the state I selected. What I want to do is pass the id of the state/province so that only that state will be highlighted. How can I add it to this or elsewhere:
onMouseEnter={() => setColor("yellow")}
The functional component:
function ColorOnHover() {
const [color, setColor] = useState("#FFF8DC");
return (
<svg>
<polygon
id="Paris"
fill={color}
stroke="#010101"
stroke-width="2"
onMouseEnter={() => setColor("yellow")}
onMouseOut={() => setColor("#FFF8DC")}
stroke-miterlimit="10"
points="1494.844,491.41 ... />
<polygon
id="Azur"
fill={color}
stroke="#010101"
stroke-width="2"
stroke-miterlimit="10"
points="638.381,931.285 .../>
</svg>
)
Upvotes: 0
Views: 881
Reputation: 96
Create a variable which basically sets color and passed it in polygon component. Also, use onMouseLeave() instead of onMouseOut().
....
const [color, setColor] = useState("#FFF8DC");
const styles = {
color: color
};
<polygon
id="Paris"
style={styles}
onMouseEnter={() => setColor("yellow")}
onMouseLeave={() => setColor("#FFF8DC")}
...
/>
)
Upvotes: 0
Reputation: 1565
Solution with css: 1. Add class attribute to svg
<svg className="country" ...>
Create and import css file
svg.country > polygon { fill: #FFF8DC; } svg.country > polygon:hover { fill: yellow; }
Upvotes: 1
Reputation: 487
If you don't have the polygon specifically for the country's capital — you have nothing to highlight. Please provide more specific example.
Also, you could solve the problem with pure CSS: just assign a class to all the polygons that are needed to be highlighted and add the :hover styles to that class that highlight a polygon the way you want.
...
UPD: Then you could try to use setState saving an id of the province and set fill property in polygon tag according to the current selectedId, something like that:
const [selectedId, setSelectedId] = useState(null)
...
<polygon
id="Paris"
fill={selectedId === 'Paris" ? 'yellow' : ''}
onMouseEnter={() => setSelectedId('Paris')}
onMouseOut={() => setSelectedId(null)}
...
/>
That's kinda explicit but you could start with something like that.
You should also try the pure CSS solution:
.highlightable:hover {
fill: yellow;
}
<polygon
id="Paris"
class="highlightable"
/>
Upvotes: 0