Strategy 3: toggle css classes
In the previous lesson, we explored how to dim elements that are not being hovered over using a CSS-only approach.
However, there are times when using JavaScript can provide more precise control over the hover effect. A handy technique is to toggle classes with JavaScript. Let’s take a look at how to do this.
🔘 Toggle Class in JavaScript
1️⃣ Create a ref
We’ve discussed the useRef React hook a few times now.
This hook allows us to target specific elements in the DOM and manipulate them with JavaScript.
// Define a ref for the graph container
const containerRef = useRef();
// Attach this ref to an element in the DOM
<svg ref={containerRef}>
<circle ... />
<circle ... />
<circle ... />
</svg>
2️⃣ Toggle classes
Once we have the containerRef
set up, we can use it to make changes to the SVG container from anywhere in the graph!
For example, we can add an onMouseEnter
property to the circle that will apply a hasHighlight
class to the SVG container:
<circle
...,
onMouseEnter={() => {
if (containerRef.current) {
containerRef.current.classList.add(styles.hasHighlight);
}
}}
onMouseLeave={() => {
if (containerRef.current) {
containerRef.current.classList.remove(styles.hasHighlight);
}
}}
/>
3️⃣ Use it for styling
A compound class selector combines multiple class names to target elements that match all of the specified classes. For example: .class1.class2
.
We can use CSS compound class selectors to apply different styles based on whether the .hasHighlight
class is present!
For example, we can set the opacity of all "slices" in the container to 1
, except when the container has the .hasHighlight
class, in which case the opacity will be set to 0.2
:
.container .slice {
opacity: 1;
cursor: pointer;
}
.container.hasHighlight .slice {
opacity: 0.2;
}
🍩 Application: Donut Chart with Hover Effect
A donut chart is a variation of the more well-known pie chart. It is easy to create using the pie()
function from D3.js.
The following example demonstrates the technique described earlier. When a slice is hovered over, a class is added to the SVG container, resulting in a CSS change for all the other slices.
A donut chart with hover interaction using the class toggle strategy.
Pros & Cons
- Fine control over interactions via JavaScript
- Performance-friendly: no re-rendering required
- Doesn't align with React’s central state management approach, which can make managing state more challenging.
More examples
The examples below all use this strategy to implement their hover effect.
Check the legend on the left hand side: it uses class toggle for its hover effect!
Visit project