Strat 3: React internal state
The 2 previous lessons describe CSS-only approaches to create hover effects. They must be used in priority because they offer the best performances.
But relying only on CSS also limits the amount of customization you can do with your hover effect. Let's understand what those limitations are, and how switching to javascript can help go further.
The problem
The CSS strategies we've seen so far are great for simple effects. But they have a fundamental limitation: CSS doesn't know your data.
Imagine a scatterplot with 3 groups. When you hover a circle from group A, you want to highlight all circles from group A. You also want to display the group name as a label.
Hover a circle — its entire group is highlighted and a label appears.
CSS alone can't do either of these things.
There are many use cases like this where custom logic is needed to decide what to do on hover. For instance: show a rectangle instead of a circle, move an element, compute a color from data, or display a label.
In those cases, we need JavaScript to write the logic.
The solution
The good news is: you already have all the knowledge to use JavaScript for hover effects.
We'll use a React state that stores information about the hovered item. Then the JSX reads this state to decide how to style elements on the chart. This gives total control!
Here is how it works, step by step:
1. Create a state
We need a state variable to track which group is currently hovered. It starts as null (nothing hovered) and can hold a group name like "A" or any additional information.
const [hoveredGroup, setHoveredGroup] = useState(null);2. Update the state on hover
Each circle gets onMouseEnter and onMouseLeave handlers that update the state with the circle's group.
Oh no! 😱
It seems like you haven't enrolled in the course yet!
Join many other students today and learn how to create bespoke, interactive graphs with d3.js and React!
Enrollment is currently closed. Join the waitlist to be notified when doors reopen:
Or Login