Display on hover
In the previous lesson, we learned how to create a Tooltip
component, position it correctly, and design its API.
Now, let’s make it appear only on hover!
1️⃣ Internal State
The first thing we need is an internal state, created with the useState
hook.
This state can be null
when nothing is hovered. If the user hovers over a graph marker, its value becomes an object of type InteractionData
, storing everything we need to know about the marker!
// Initialize an internal state
const [interactionData, setInteractionData] = useState<InteractionData | null>(null);
2️⃣ Updating the State on Hover
The setInteractionData
function allows us to update this state. We can use it to update interactionData
whenever a graph marker is hovered over!
For example, if the marker is a circle, as in a scatterplot, the code might look like this:
<circle
r={8}
cx={250}
cy={150}
onMouseEnter={() => // Each time the circle is hovered hover...
setInteractionData({ // ... update the interactionData state with the circle information
xPos: 250,
yPos: 150,
name: "hello",
})
}
onMouseLeave={() => setInteractionData(null)} // When the user stops hovering, reset the interactionData to null
/>
3️⃣ Conditionally Render the Tooltip
The Tooltip
component takes interactionData
(the internal state) as a prop.
If interactionData
is null
, the component returns nothing, so the tooltip appears only when interactionData
has a value—i.e., when the user hovers over a marker.
Don’t forget to add
pointerEvents: "none"
to thediv
that wraps theTooltip
component! Otherwise, theonMouseEnter()
event on SVG elements won’t be triggered.
Scatterplot minimal example
Let's apply what we learnt on a scatterplot, creating a minimal tooltip:
Scatterplot with tooltip. Hover over a circle to get the corresponding country name.