Bending the Rules of CSS View Transitions - Animating a Mega Menu

In this article we showcase making on-page animations using View Transitions, with a focus on recreating Stripe's Mega Menu using surprisingly little code.

Code on Github
🧑‍💻 🎥
... Almost ready!

View transitions is a relatively new CSS API that is mainly showcased when making nice animations going from one page to another. But in the end view transitions are based on animating updates that happen in the DOM – which could very well be small animations on a page. In this article we explore excactly that, by recreating Stripe’s mega menu using surprisingly little code.

The basics of view transitions

The view transitions API is based around the document.startViewTransition() function. Any update you do within that function, is automatically animated.

document.startViewTransition(() => {
// Update the DOM in here
updateTheDomInHere();
});

This DOM update could be the rendering of a whole new page, or a small element that changes on the page. Such a small element could for example be a dropdown menu.

Toggling a dropdown

Let’s start by creating a simple dropdown menu, that we can toggle open and closed by clicking a button or focussing that button.

This dropdown menu uses a button with an onfocus and an onclick handler to toggle it’s submenu:

<button
onFocus={() => setActiveSub(item.id)}
onClick={() => setActiveSub(item.id)}
></button>

On top of that you also find another pointerLeave and pointerEnter event in the example, setting the state of the sub navigation.

Adding an animation

When the user toggles a different dropdown, we right now trigger a setState that ensures the correct dropdown is opened. If we want to animate this with view transitions, we should add the following.

import { flushSync } from "react-dom";
const [activeSub, _setActiveSub] = useState<null | number>(null);
const setActiveSub = (id: number | null) => {
document.startViewTransition(() => {
flushSync(() => {
_setActiveSub(id);
});
});
}

Note that we renamed the setActiveSub function to _setActiveSub and created a new setActiveSub function that wraps the original one. This way instead of directly updating the state, we do this via the document.startViewTransition function.

On top of that we also wrap this in the flushSync function by React, which ensures the state is updated synchronously. If you would then run that code, you get the result below.

The first thing you notice, is a flickering in the dropdown menu. Disable the onPointerLeave with the button, to see the navigation working without it. (Move your cursor over ‘pricing’ to close the submenu now 😅)

Why the flickering?

We’ve now encountered the first challenge with view transitions, showcasing why we’re slightly bending the rules. The current way view transitions are built, is in such a way that whenever the animation is happening, the document freezes its current state. This means you have no way of interacting with the page during that moment, and thus hover, focus and any other events stop working. Causing our onPointerLeave to fire, and the menu to close.

Let’s first appreciate the animation

But before we continue solving the flicker, let’s first appreciate the animation we already get with these few lines added! By default, if you don’t specify anything else, the browser fades the two states into each other. That’s the animation you see now.

You can however configure that animation in any way you want. The most easy step is by telling the browser to animate individual elements, instead of the whole page. You do that by giving specific elements a CSS property view-transition-name.

<div
id={`subnav-${item.id}`}
className="[view-transition-name:subnav] absolute left-0 top-full hidden w-[500px] rounded-lg bg-white p-1 text-black peer-aria-expanded:block"
></div>

This Tailwind class adds the equivalent of view-transition-name: subnav;. And doing so, results in the following amazing animation:

To me it feels crazy, that by only adding a single CSS property we can go from a basic fade animation to such a nice animation!

Let’s solve the flickering next

Like I explained before, the flickering is caused by the fact that the document freezes during the animation, and we thus trigger the pointerLeave event.

As long as there is no interruptability in view transitions yet, we need to come up with our own solution to get this to work. The solution I came up with was storing a boolean in state when an animation is happening, and if a pointerLeave happens during that time, we ignore it. Like so.

const [activeSub, _setActiveSub] = useState<null | number>(null);
const isTranstioningRef = useRef(false);
const setActiveSub = useCallback(
async (id: number | null) => {
if (isTranstioningRef.current || id === activeSub) return;
const transition = document.startViewTransition(() => {
flushSync(() => {
isTranstioningRef.current = true;
_setActiveSub(id);
});
});
await transition.finished;
isTranstioningRef.current = false;
},
[activeSub],
);

There are a few things happening here at once. Make sure to watch the full video to get a better explanation on each step.

  1. On line 2 we create a isTranstioningRef that we use to store if an animation is happening.
  2. We do this in a ref, so our setActiveSub won’t create a new instance of itself, when running
  3. On line 6 we check if an animation is happening, or if we are trying to open the same submenu. If so, we return early and don’t run the animation again.
  4. On line 8 we start the animation, and set the isTranstioningRef to true.
  5. On line 16 we await the animation to finish, and set the isTranstioningRef to false again. The transition variable here is also new, it’s being returned by the view transition function.

By combining these extra checks, we can now prevent the menu from closing when the animation is happening. A small “hack” we need to apply now, until you can interrupt view transition animations.

Customizing the animation even further

Why stop here? We can even make the subnavigation come from either the left or the right side, depending on where your cursor is. Just like Stripe’s navigation. Watch the full video on adding animations with view transitions on Youtube, to see how we do that, or take a look at the code below!

Eager to learn more?

I think this video might be a good fit for you too!