Components

Transitions

A transition runs Vue's enter and leave classes on an element as a condition shows or hides it, so your CSS animates it on every framework.

Transitions let an element fade, slide or grow as a condition shows or hides it, like a menu that fades out, an accordion panel that opens or a toast that pops in. In Unframework you wrap the element in <Transition>, and it gets Vue's enter and leave classes, which your stylesheet animates. Think of a menu that vanishes in the middle of its fade, a panel that jumps open with no transition at all, or a timer that guesses how long the animation takes before it removes the element.

This page walks you through animating what a condition renders. We'll look at:

  • A transition on a condition: the classes, and what each framework does.
  • Swapping two elements: a ternary or an else-if chain, where one leaves as the other enters.
  • What the compiler checks: the child, name and appear.
  • What isn't guaranteed: the timing that differs between frameworks.

A transition on a condition

Import Transition and put it around a condition. It holds one element, or one conditional whose every branch is one element. name is the prefix of its classes, v when you leave it out:

Menu.uf.tsx
import "./Menu.css";
import { Transition, ref } from "@uxfront/unframework";

// A menu, open at first, that leaves with the `fade` transition.
export default function Menu() {
  const open = ref(true);

  return (
    <nav class="menu" aria-label="Account">
      <button type="button" aria-expanded={open.value} onClick={() => (open.value = !open.value)}>
        Account
      </button>
      <Transition name="fade">
        {open.value && (
          <ul class="items">
            <li>Profile</li>
            <li>Sign out</li>
          </ul>
        )}
      </Transition>
    </nav>
  );
}

When the element enters, it carries fade-enter-from and fade-enter-active before it is first painted. Two frames later, fade-enter-from goes and fade-enter-to comes, and at the end of its transition both others go too. Leaving runs the same with fade-leave-from, fade-leave-active and fade-leave-to, and the element stays in its place until its transition ends. So the stylesheet gives the -active classes a transition, and the -from or -to classes the state the element animates from or to:

Menu.css
.menu {
  padding: 8px;
  background-color: rgb(243, 244, 246);
}

.items {
  margin: 8px 0 0;
  padding-left: 16px;
}

.fade-enter-active,
.fade-leave-active {
  transition: opacity 100ms ease;
}

.fade-enter-from,
.fade-leave-to {
  opacity: 0;
}

The end is the element's own transitionend or animationend, or its longest duration and delay, whichever comes first. With no transition in the stylesheet, the classes come and go within two frames. The server renders the settled menu, with no class of the transition.

Vue writes its own <Transition>. React, Solid and Qwik run the classes with a small helper that keeps the leaving element in the DOM until its leave ends, Svelte with transition functions on in: and out:, and Angular with a directive and animate.leave. Astro renders once, on the server, so it renders the settled child:

Menu.tsx
import {
  type CSSProperties,
  type ReactElement,
  type ReactNode,
  type Ref,
  cloneElement,
  useCallback,
  useLayoutEffect,
  useRef,
  useState,
  useSyncExternalStore,
} from "react";
import "./Menu.uf.tsx.css";

export interface MenuAttributes {
  className?: string;
  style?: CSSProperties;
}

export default function Menu({ className, style, ...attributes }: MenuAttributes) {
  const [open, setOpen] = useState(true);
  const openRef = useRef(open);

  return (
    <nav
      className={cx("menu", className)}
      aria-label="Account"
      style={style}
      data-uf-e688a71a=""
      {...scopeAttributes(attributes)}
    >
      <button
        type="button"
        aria-expanded={open}
        onClick={() => {
          openRef.current = !openRef.current;
          setOpen(openRef.current);
        }}
        data-uf-e688a71a=""
      >
        Account
      </button>
      <Transition name="fade">
        {open ? (
          <ul key={0} className="items" data-uf-e688a71a="">
            <li data-uf-e688a71a="">Profile</li>
            <li data-uf-e688a71a="">Sign out</li>
          </ul>
        ) : null}
      </Transition>
    </nav>
  );
}

/** Joins class names, and the keys of an object's truthy entries, into one `className`. */
function cx(...parts: unknown[]): string {
  const names: string[] = [];
  for (const part of parts) {
    if (typeof part === "string") {
      if (part) names.push(part);
    } else if (part && typeof part === "object") {
      for (const [key, on] of Object.entries(part)) {
        if (on) names.push(key);
      }
    }
  }
  return names.join(" ");
}

/** The scope attributes of the styled parents that render this component, for its root. */
function scopeAttributes(props: object): Record<string, ""> {
  const scope: Record<string, ""> = {};
  for (const key of Object.keys(props)) {
    if (key.startsWith("data-uf-")) scope[key] = "";
  }
  return scope;
}

/** One element a `Transition` renders: its key, its last render and the phase it is in. */
interface TransitionEntry {
  key: string;
  node: ReactElement<{ className?: string; ref?: Ref<Element> }>;
  phase?: "enter" | "leave";
  step: "from" | "to";
  time: number;
}

/** Subscribes to nothing: whether the component renders on a client never changes once it does. */
function subscribeNothing(): () => void {
  return () => {};
}

/**
 * Runs Vue's transition classes of `name` on the element `children` renders, keyed by its
 * branch, as it enters and leaves: `-from` and `-active` first, `-to` for `-from` two frames
 * later, and none once the element's own `transitionend` or `animationend` fires, or its longest
 * duration and delay pass. A leaving element stays, as it last rendered, until its leave ends.
 */
function Transition({
  name,
  appear = false,
  children,
}: {
  name: string;
  appear?: boolean;
  children: ReactElement<{ className?: string; ref?: Ref<Element> }> | null;
}): ReactNode {
  // False on the server and while the client hydrates: only a client mount runs `appear`.
  const client = useSyncExternalStore(
    subscribeNothing,
    () => true,
    () => false,
  );
  const [shown, setShown] = useState(children);
  const [entries, setEntries] = useState<TransitionEntry[]>(() =>
    children
      ? [
          {
            key: String(children.key),
            node: children,
            ...(appear && client ? { phase: "enter" as const } : {}),
            step: "from",
            time: 0,
          },
        ]
      : [],
  );
  const elements = useRef(new Map<string, Element>());
  const [register] = useState(() => (key: string, element: Element | null) => {
    if (element) elements.current.set(key, element);
    else elements.current.delete(key);
  });
  if (children !== shown) {
    setShown(children);
    const before = shown === null ? undefined : String(shown.key);
    const after = children === null ? undefined : String(children.key);
    if (before !== after) {
      // The shown element leaves as it last rendered, and the new one enters.
      const next = entries.flatMap((each): TransitionEntry[] => {
        if (each.key === after) return [];
        return each.key === before && each.phase !== "leave" && shown
          ? [{ key: each.key, node: shown, phase: "leave", step: "from", time: 0 }]
          : [each];
      });
      if (children && after !== undefined)
        next.push({ key: after, node: children, phase: "enter", step: "from", time: 0 });
      setEntries(next);
    }
  }
  useLayoutEffect(() => {
    const stops: (() => void)[] = [];
    const settle = (entry: TransitionEntry) =>
      setEntries((list) =>
        entry.phase === "leave"
          ? list.filter((each) => each !== entry)
          : list.map((each) =>
              each === entry ? { key: each.key, node: each.node, step: "from", time: 0 } : each,
            ),
      );
    for (const entry of entries) {
      const element = elements.current.get(entry.key);
      if (!entry.phase || !element) continue;
      if (entry.step === "from") {
        let frame = requestAnimationFrame(() => {
          frame = requestAnimationFrame(() => {
            const style = getComputedStyle(element);
            const longest = (delays: string, durations: string) => {
              const each = (list: string) =>
                list.split(", ").map((time) => Number(time.slice(0, -1)) * 1000);
              const delay = each(delays);
              return Math.max(
                0,
                ...each(durations).map(
                  (duration, index) => duration + (delay[index % delay.length] ?? 0),
                ),
              );
            };
            const time = Math.max(
              longest(style.transitionDelay, style.transitionDuration),
              longest(style.animationDelay, style.animationDuration),
            );
            if (!time) settle(entry);
            else
              setEntries((list) =>
                list.map((each) => (each === entry ? { ...each, step: "to", time } : each)),
              );
          });
        });
        stops.push(() => cancelAnimationFrame(frame));
        continue;
      }
      const end = (event?: Event) => {
        if (event && event.target !== element) return;
        settle(entry);
      };
      element.addEventListener("transitionend", end);
      element.addEventListener("animationend", end);
      const timer = setTimeout(end, entry.time + 1);
      stops.push(() => {
        clearTimeout(timer);
        element.removeEventListener("transitionend", end);
        element.removeEventListener("animationend", end);
      });
    }
    return () => {
      for (const stop of stops) stop();
    };
  }, [entries]);
  return entries.map((entry) => {
    const node = entry.phase === "leave" || !children ? entry.node : children;
    const classes = entry.phase
      ? [`${name}-${entry.phase}-${entry.step}`, `${name}-${entry.phase}-active`]
      : [];
    return (
      <TransitionItem
        key={entry.key}
        id={entry.key}
        node={node}
        className={[node.props.className, ...classes].filter(Boolean).join(" ") || undefined}
        register={register}
      />
    );
  });
}

/** Renders one element of a `Transition` with its classes, its own ref kept beside the transition's. */
function TransitionItem({
  id,
  node,
  className,
  register,
}: {
  id: string;
  node: ReactElement<{ className?: string; ref?: Ref<Element> }>;
  className: string | undefined;
  register: (key: string, element: Element | null) => void;
}): ReactNode {
  const own = node.props.ref;
  const ref = useCallback(
    (element: Element) => {
      register(id, element);
      const detach = attachRef(own, element);
      return () => {
        register(id, null);
        detach();
      };
    },
    [id, own, register],
  );
  return cloneElement(node, { className, ref });
}

/** Gives a ref the element, as React would, and returns what takes it back. */
function attachRef(ref: Ref<Element> | undefined, element: Element): () => void {
  if (typeof ref === "function") {
    const cleanup = ref(element);
    return typeof cleanup === "function" ? cleanup : () => ref(null);
  }
  if (ref) ref.current = element;
  return () => {
    if (ref) ref.current = null;
  };
}

appear runs the enter when the element first mounts on the client too, such as a toast that pops in: <Transition name="pop" appear>. Without it, only a change of the condition runs a transition.

Swapping two elements

A ternary or an else-if chain in a <Transition> swaps one element for another. The old one runs its leave while the new one runs its enter, so both are in the DOM until the leave ends, and then only the new one stays. A swap transitions even when both branches are the same tag:

Steps.uf.tsx
import "./Steps.css";
import { Transition, ref } from "@uxfront/unframework";

// Two conditionals of one tag in a transition each: a ternary swap, and an else-if chain.
export default function Steps() {
  const first = ref(true);
  const step = ref(1);

  return (
    <section class="steps" aria-label="Checkout">
      <button type="button" onClick={() => (first.value = !first.value)}>
        Swap
      </button>
      <Transition name="swap">
        {first.value ? <p class="card">Cart</p> : <p class="card">Payment</p>}
      </Transition>
      <button type="button" onClick={() => (step.value = (step.value % 3) + 1)}>
        Next
      </button>
      <Transition name="step">
        {step.value === 1 ? (
          <p class="step">Step one</p>
        ) : step.value === 2 ? (
          <p class="step">Step two</p>
        ) : (
          <p class="step">Step three</p>
        )}
      </Transition>
    </section>
  );
}

The two elements sit side by side while they swap, so give the -leave-active class a position: absolute if the old one shouldn't push the new one down.

What the compiler checks

<Transition> holds one element, or one conditional whose every branch is one element or nothing. Two elements, text or a component as its child is rejected, UF3057: wrap a component in an element, and keep the condition inside the <Transition>:

Disclosure.uf.tsx
// UF3057 transition-child: `<Transition>` holds one element, or one conditional of elements, so
// two elements, text and a component as its child are rejected.
import { Transition } from "@uxfront/unframework";

function Hint() {
  return <p>Hint</p>;
}

export default function Disclosure() {
  return (
    <section>
      <Transition>
        <p>First</p>
        <p>Second</p>
      </Transition>
      <Transition>Saved</Transition>
      <Transition>
        <Hint />
      </Transition>
    </section>
  );
}

name is a string literal that isn't empty, and appear is the bare attribute, {true} or {false}. A bound name, an empty one or a bound appear is rejected, UF3058: to switch between two transitions, write two <Transition> elements in a conditional.

A <Transition> inside a list's body isn't supported yet: transitions on a list's rows are TransitionGroup's, which is still to come. mode and JavaScript hooks aren't supported either. A component whose whole render is a <Transition> takes no class or style from its parent, UF3045.

What isn't guaranteed

The child goes at once, with no leave, when the component that holds the <Transition> unmounts or a condition around the <Transition> turns false, as on Vue. Only a change of the transition's own child runs a leave. A few things differ between frameworks:

  • Whether appear's enter runs as a server render hydrates. The page settles to the server's HTML either way.
  • The order of the two elements while they swap.
  • How it looks when the condition turns back while the leave still runs. Vue removes the leaving element and enters a new one, Svelte reverses the leave, and Angular keeps the old element leaving beside the new one. Either way the element ends with no class of the transition.
  • Whether a leaving element still updates. It keeps its last render everywhere but in Qwik.
  • When a directive's unmounted runs on an element that leaves. It runs when the leave starts on Vue, Solid and Angular, and when it ends on React, Svelte and Qwik, so by the end of the leave it has run everywhere.
  • A bound class on the element that changes during a transition, which can cut it short.
  • prefers-reduced-motion, which no framework reads for you, as Vue doesn't. Give the -active classes no transition inside a @media (prefers-reduced-motion: reduce) rule.
  • How long Svelte keeps a leaving element: it reads the element's duration as the leave starts, rather than waiting for transitionend.

The tests of your components see each transition settled: the harness waits for every running transition and animation to end before it captures the page. The decision behind this page is ADR-0100. The rule is on the semantics page.

Copyright © 2026