---
title: "Hover preview"
url: "https://sarthakmishra.com/riff-ui/components/hover-preview"
description: "List whose rows show a floating image card that trails the cursor. Accessible React 19 source on UI SDK, installed with the shadcn CLI."
image: "https://sarthakmishra.com/og-images/riff-ui/hover-preview.webp"
---

[View HTML](https://sarthakmishra.com/riff-ui/components/hover-preview) · [Site index](https://sarthakmishra.com/llms.txt)

# Hover preview

List whose rows show a floating image card that trails the cursor.

## Installation

### CLI

```bash
pnpm dlx shadcn@latest add @riff/hover-preview
```

### Manual

1. Copy the component

   Save this as `components/ui/hover-preview.tsx`:

   ```tsx
   'use client';
   import {
     useLayoutEffect,
     useRef,
     useState,
     type CSSProperties,
     type ReactNode,
   } from 'react';
   import { createPortal } from 'react-dom';
   import './hover-preview.css';

   type CustomProperties = CSSProperties & Record<`--${string}`, string | number>;
   /** Custom properties for `style`, typed without a global declaration. */
   const cssVars = (values: CustomProperties): CSSProperties => values;

   export type HoverPreviewItem = {
     id: string;
     href: string;
     title: ReactNode;
     /** Secondary text at the row's end, such as a date or a count. */
     meta?: ReactNode;
     /** The card's image; rows without one show a gradient seeded by `id`. */
     image?: string;
   };

   type Point = { x: number; y: number };

   // Room between the pointer and the card, and the card and the viewport edge.
   const OFFSET = 24;
   const MARGIN = 12;
   // Time for the card to close about two-thirds of the gap to the pointer.
   const FOLLOW_MS = 70;

   /** Right of the pointer and centred on it, flipped left near the edge. */
   function place(pointer: Point, width: number, height: number) {
     const fitsRight = pointer.x + OFFSET + width <= innerWidth - MARGIN;
     const x = fitsRight ? pointer.x + OFFSET : pointer.x - OFFSET - width;
     const y = Math.min(
       Math.max(pointer.y - height / 2, MARGIN),
       Math.max(innerHeight - MARGIN - height, MARGIN),
     );
     return { x: Math.max(x, MARGIN), y, side: fitsRight ? 'right' : 'left' };
   }

   /** A stable hash, so a row keeps its gradient across renders and builds. */
   function hash(text: string) {
     let value = 2166136261;
     for (const char of text) {
       value ^= char.codePointAt(0) ?? 0;
       value = Math.imul(value, 16777619);
     }
     return value >>> 0;
   }

   const HUES = [25, 85, 150, 230, 285, 340];

   /** Three soft colour fields, seeded by the row's id. */
   function mesh(id: string): CSSProperties {
     const seed = hash(id);
     const hue = HUES[seed % HUES.length] ?? 25;
     const field = (index: number) => {
       const bits = (seed >>> (index * 8 + 4)) & 0xff;
       return `${10 + (bits % 80)}% ${10 + ((bits * 7) % 80)}%`;
     };
     return cssVars({
       '--riff-hover-a': `oklch(0.75 0.14 ${hue})`,
       '--riff-hover-b': `oklch(0.8 0.12 ${hue + 50})`,
       '--riff-hover-c': `oklch(0.7 0.13 ${hue + 150})`,
       '--riff-hover-1': field(0),
       '--riff-hover-2': field(1),
       '--riff-hover-3': field(2),
     });
   }

   const finePointer = '(hover: hover) and (pointer: fine)';

   /**
    * A list of links. Under a mouse, a card floats beside the pointer showing
    * the hovered row's image; moving down the list slides the next image up
    * into place, moving up slides it down. Touch and keyboard use the plain
    * links.
    */
   export function HoverPreviewList({
     items,
     label,
   }: {
     items: readonly HoverPreviewItem[];
     /** Names the list for screen readers. */
     label?: string;
   }) {
     const list = useRef<HTMLUListElement>(null);
     const card = useRef<HTMLDivElement>(null);
     const [active, setActive] = useState<number>();
     const [visible, setVisible] = useState(false);
     // The card and its images mount on the first mouse move over the list.
     const [engaged, setEngaged] = useState(false);

     useLayoutEffect(() => {
       const element = list.current;
       if (!element) return;
       let pointer: Point | null = null;
       let current: Point | null = null;
       let raf = 0;
       let last = 0;
       const draw = (now: number) => {
         raf = 0;
         const frame = card.current;
         if (!frame || !pointer) return;
         const target = place(pointer, frame.offsetWidth, frame.offsetHeight);
         const snap =
           !current ||
           !last ||
           matchMedia('(prefers-reduced-motion: reduce)').matches;
         // Exponential smoothing, the same feel at 60 and 120 Hz.
         const t = snap ? 1 : 1 - Math.exp(-Math.max(now - last, 0) / FOLLOW_MS);
         const from = current ?? target;
         current = {
           x: from.x + (target.x - from.x) * t,
           y: from.y + (target.y - from.y) * t,
         };
         last = now;
         frame.dataset.side = target.side;
         frame.style.transform = `translate3d(${current.x}px, ${current.y}px, 0)`;
         if (
           Math.abs(current.x - target.x) > 0.1 ||
           Math.abs(current.y - target.y) > 0.1
         )
           raf = requestAnimationFrame(draw);
         else last = 0;
       };
       const show = () => {
         if (!pointer) return;
         const row = document
           .elementFromPoint(pointer.x, pointer.y)
           ?.closest<HTMLElement>('[data-preview-index]');
         const inside = row !== null && row !== undefined && element.contains(row);
         if (inside) setActive(Number(row.dataset.previewIndex));
         setVisible(inside);
         if (!raf) raf = requestAnimationFrame(draw);
       };
       const move = (event: PointerEvent) => {
         if (event.pointerType !== 'mouse' || !matchMedia(finePointer).matches)
           return;
         pointer = { x: event.clientX, y: event.clientY };
         setEngaged(true);
         show();
       };
       const leave = () => {
         pointer = null;
         current = null;
         last = 0;
         cancelAnimationFrame(raf);
         raf = 0;
         setVisible(false);
       };
       element.addEventListener('pointermove', move);
       element.addEventListener('pointerleave', leave);
       addEventListener('scroll', show, { passive: true });
       return () => {
         element.removeEventListener('pointermove', move);
         element.removeEventListener('pointerleave', leave);
         removeEventListener('scroll', show);
         cancelAnimationFrame(raf);
       };
     }, []);

     return (
       <>
         <ul ref={list} className="riff-hover-list" aria-label={label}>
           {items.map((item, index) => (
             <li key={item.id}>
               <a
                 href={item.href}
                 className="riff-hover-row"
                 data-preview-index={index}
               >
                 <span className="riff-hover-title">{item.title}</span>
                 {item.meta && (
                   <span className="riff-hover-meta">{item.meta}</span>
                 )}
               </a>
             </li>
           ))}
         </ul>
         {engaged &&
           createPortal(
             <div
               ref={card}
               className="riff-hover-card"
               data-visible={visible ? '' : undefined}
               aria-hidden="true"
             >
               <div className="riff-hover-frame">
                 {items.map((item, index) => {
                   let position = 'active';
                   if (active === undefined || index < active) position = 'before';
                   else if (index > active) position = 'after';
                   return item.image ? (
                     <img
                       key={item.id}
                       className="riff-hover-image"
                       data-position={position}
                       src={item.image}
                       alt=""
                       decoding="async"
                     />
                   ) : (
                     <span
                       key={item.id}
                       className="riff-hover-image riff-hover-mesh"
                       data-position={position}
                       style={mesh(item.id)}
                     />
                   );
                 })}
               </div>
             </div>,
             document.body,
           )}
       </>
     );
   }
   ```

2. Copy its styles

   Save this beside it as `hover-preview.css`:

   ```css
   /* Host roles first, system colours after: the component reads your theme
      when it has these properties and stays legible when it does not. */
   @layer components {
     .riff-hover-list {
       display: flex;
       flex-direction: column;
       margin: 0;
       padding: 0;
       list-style: none;
     }
     .riff-hover-row {
       display: flex;
       min-height: 2.5rem;
       align-items: center;
       gap: 1rem;
       border-radius: 0.5rem;
       padding: 0.5rem 0.75rem;
       color: var(--color-foreground, CanvasText);
       font-size: 0.9375rem;
       text-decoration: none;
       transition: background-color 150ms cubic-bezier(0, 0, 0.2, 1);
       &:focus-visible {
         outline: 2px solid var(--color-ring, Highlight);
         outline-offset: -2px;
       }
     }
     .riff-hover-title {
       min-width: 0;
       flex: 1;
       overflow: hidden;
       text-overflow: ellipsis;
       white-space: nowrap;
     }
     .riff-hover-meta {
       flex: none;
       color: var(--color-muted-foreground, GrayText);
       font-size: 0.8125rem;
       font-variant-numeric: tabular-nums;
     }
     @media (hover: hover) {
       .riff-hover-row:hover {
         background-color: var(--color-muted, ButtonFace);
       }
     }

     /* The floating card. Its frame is moved by script every frame; the inner
        card owns the enter and exit so the two transforms never compete. */
     .riff-hover-card {
       position: fixed;
       z-index: 50;
       top: 0;
       left: 0;
       pointer-events: none;
     }
     .riff-hover-frame {
       position: relative;
       width: var(--riff-hover-width, 18rem);
       overflow: hidden;
       border: 1px solid var(--color-border, GrayText);
       border-radius: 0.75rem;
       aspect-ratio: 16 / 10;
       background-color: var(--color-muted, Canvas);
       box-shadow: 0 20px 40px rgb(0 0 0 / 18%);
       opacity: 0;
       scale: 0.9;
       transform-origin: left center;
       transition:
         opacity 150ms cubic-bezier(0, 0, 0.2, 1),
         scale 150ms cubic-bezier(0, 0, 0.2, 1);
       .riff-hover-card[data-side='left'] & {
         transform-origin: right center;
       }
       .riff-hover-card[data-visible] & {
         opacity: 1;
         scale: 1;
         transition-duration: 200ms;
       }
     }
     /* Images wait above or below the active one and slide in from the side
        the pointer came from; blur hides the crossfade's double exposure. */
     .riff-hover-image {
       position: absolute;
       inset: 0;
       width: 100%;
       height: 100%;
       object-fit: cover;
       opacity: 0;
       filter: blur(6px);
       transition:
         opacity 200ms cubic-bezier(0, 0, 0.2, 1),
         translate 300ms cubic-bezier(0, 0, 0.2, 1),
         filter 200ms cubic-bezier(0, 0, 0.2, 1);
       &[data-position='before'] {
         translate: 0 -14%;
       }
       &[data-position='after'] {
         translate: 0 14%;
       }
       &[data-position='active'] {
         opacity: 1;
         filter: none;
       }
     }
     .riff-hover-mesh {
       background-color: color-mix(in oklch, var(--riff-hover-a) 25%, Canvas);
       background-image:
         radial-gradient(
           at var(--riff-hover-1),
           var(--riff-hover-a) 0,
           transparent 55%
         ),
         radial-gradient(
           at var(--riff-hover-2),
           var(--riff-hover-b) 0,
           transparent 55%
         ),
         radial-gradient(
           at var(--riff-hover-3),
           var(--riff-hover-c) 0,
           transparent 55%
         );
     }
     @media (prefers-reduced-motion: reduce) {
       .riff-hover-row {
         transition: none;
       }
       .riff-hover-frame,
       .riff-hover-card[data-visible] .riff-hover-frame {
         scale: 1;
       }
       .riff-hover-image {
         filter: none;
         &[data-position='before'],
         &[data-position='after'] {
           translate: none;
         }
       }
     }
   }
   ```

## Usage

```tsx
import { HoverPreviewList } from '@/components/ui/hover-preview';

<HoverPreviewList
  items={[{ id: 'one', href: '/work/one', title: 'Project one', image: '/one.webp' }]}
/>;
```

Hover a row with a mouse: the card trails the pointer, flips to the left near the edge, and slides between images in the direction you move. The card and its images load on the first hover. Touch and keyboard use the plain links.

## Props

| Prop    | Type                 | Default | Description                                                  |
| ------- | -------------------- | ------- | ------------------------------------------------------------ |
| `items` | `HoverPreviewItem[]` |         | Each `id`, `href`, `title`, and optional `meta` and `image`. |
| `label` | `string`             |         | Names the list.                                              |

## Structured data

```json
{
  "@context": "https://schema.org",
  "@graph": [
    {
      "@type": "WebSite",
      "@id": "https://sarthakmishra.com/#website",
      "url": "https://sarthakmishra.com/",
      "name": "Sarthak Mishra",
      "publisher": {
        "@id": "https://sarthakmishra.com/#person"
      },
      "inLanguage": "en"
    },
    {
      "@type": "Person",
      "@id": "https://sarthakmishra.com/#person",
      "name": "Sarthak Mishra",
      "url": "https://sarthakmishra.com/about",
      "jobTitle": "Design Engineer",
      "image": "https://sarthakmishra.com/og-images/sarthak-mishra.webp",
      "sameAs": [
        "https://github.com/SarthakMishra",
        "https://www.linkedin.com/in/itssarthakmishra/",
        "https://x.com/MishraMishry"
      ]
    },
    {
      "@type": "WebPage",
      "@id": "https://sarthakmishra.com/riff-ui/components/hover-preview#webpage",
      "url": "https://sarthakmishra.com/riff-ui/components/hover-preview",
      "name": "Hover preview React Component - Riff UI",
      "description": "List whose rows show a floating image card that trails the cursor. Accessible React 19 source on UI SDK, installed with the shadcn CLI.",
      "inLanguage": "en",
      "isPartOf": {
        "@id": "https://sarthakmishra.com/#website"
      },
      "about": {
        "@id": "https://sarthakmishra.com/#person"
      }
    }
  ]
}
```
