Comparador antes y después
Control que divide dos capas con arrastre y teclado (flechas, Inicio, Fin); sirve para cualquier contenido.
AntesDespués
Código completo
Es exactamente el archivo que se descarga. Cópialo a tu proyecto y úsalo.
"use client";
import { useRef, useState, type CSSProperties, type KeyboardEvent, type PointerEvent, type ReactNode } from "react";
/** Comparador antes/después: un control deslizante divide dos capas con arrastre, teclado y etiquetas. Las capas son cualquier contenido, aquí dos ilustraciones propias. Minimalista. React + TypeScript, sin dependencias. */
export type DatosComparadorProps = {
before?: ReactNode;
after?: ReactNode;
beforeLabel?: string;
afterLabel?: string;
defaultValue?: number;
className?: string;
style?: CSSProperties;
};
const CSS = `
.gcdcm-root { box-sizing: border-box; position: relative; width: 100%; max-width: 560px; aspect-ratio: 16 / 10; overflow: hidden; border-radius: 16px; background: #111; color: #fff; font: 600 12px/1 ui-sans-serif, system-ui, -apple-system, "Segoe UI", sans-serif; user-select: none; touch-action: pan-y; cursor: ew-resize; }
.gcdcm-root *, .gcdcm-root *::before, .gcdcm-root *::after { box-sizing: border-box; }
@media (prefers-reduced-motion: reduce) { .gcdcm-root * { transition-duration: .01ms !important; } }
.gcdcm-layer { position: absolute; inset: 0; }
.gcdcm-layer > * { width: 100%; height: 100%; display: block; }
.gcdcm-after { clip-path: inset(0 0 0 var(--x)); }
.gcdcm-tag { position: absolute; top: 14px; padding: 6px 10px; border-radius: 6px; background: rgba(0, 0, 0, .55); letter-spacing: .06em; text-transform: uppercase; pointer-events: none; }
.gcdcm-line { position: absolute; top: 0; bottom: 0; left: var(--x); width: 2px; margin-left: -1px; background: #fff; box-shadow: 0 0 0 1px rgba(0, 0, 0, .15); pointer-events: none; }
.gcdcm-handle { position: absolute; top: 50%; left: var(--x); display: grid; place-items: center; width: 44px; height: 44px; margin: -22px 0 0 -22px; padding: 0; border: 0; border-radius: 50%; background: #fff; color: #111; cursor: ew-resize; box-shadow: 0 4px 14px rgba(0, 0, 0, .4); transition: transform .15s; }
.gcdcm-handle:hover { transform: scale(1.08); }
.gcdcm-handle:focus-visible { outline: 3px solid #5aa9ff; outline-offset: 3px; }`;
const Before = (
<svg viewBox="0 0 160 100" preserveAspectRatio="xMidYMid slice" aria-hidden="true">
<rect width="160" height="100" fill="#c9c4b8" />
<path d="M0 78h160v22H0z" fill="#a49d8d" />
<rect x="18" y="26" width="46" height="36" fill="#8f897b" />
<rect x="76" y="18" width="30" height="44" fill="#9a9484" />
<rect x="116" y="30" width="30" height="32" fill="#8a8476" />
<path d="M10 70l20-10 15 8" stroke="#6d675a" strokeWidth="1.5" fill="none" />
<rect x="22" y="32" width="8" height="8" fill="#b9b3a4" /><rect x="36" y="32" width="8" height="8" fill="#b9b3a4" />
</svg>
);
const After = (
<svg viewBox="0 0 160 100" preserveAspectRatio="xMidYMid slice" aria-hidden="true">
<rect width="160" height="100" fill="#cfe9ff" />
<path d="M0 78h160v22H0z" fill="#5bbf8a" />
<rect x="18" y="26" width="46" height="36" fill="#ff7a59" />
<rect x="76" y="18" width="30" height="44" fill="#2f5bff" />
<rect x="116" y="30" width="30" height="32" fill="#ffd23f" />
<circle cx="136" cy="14" r="8" fill="#ffe77a" />
<rect x="22" y="32" width="8" height="8" fill="#fff" opacity=".85" /><rect x="36" y="32" width="8" height="8" fill="#fff" opacity=".85" />
</svg>
);
export function DatosComparador({ before = Before, after = After, beforeLabel = "Antes", afterLabel = "Después", defaultValue = 50, className = "", style }: DatosComparadorProps) {
const [x, setX] = useState(defaultValue);
const ref = useRef<HTMLDivElement>(null);
const drag = useRef(false);
function fromPointer(event: PointerEvent) {
const rect = ref.current!.getBoundingClientRect();
setX(Math.max(0, Math.min(100, ((event.clientX - rect.left) / rect.width) * 100)));
}
function key(event: KeyboardEvent) {
const step = event.shiftKey ? 10 : 2;
if (event.key === "ArrowLeft") { event.preventDefault(); setX((v) => Math.max(0, v - step)); }
if (event.key === "ArrowRight") { event.preventDefault(); setX((v) => Math.min(100, v + step)); }
if (event.key === "Home") { event.preventDefault(); setX(0); }
if (event.key === "End") { event.preventDefault(); setX(100); }
}
return (
<div ref={ref} className={`gcdcm-root ${className}`} style={{ "--x": `${x}%`, ...style } as CSSProperties} onPointerDown={(event) => { drag.current = true; (event.currentTarget as HTMLElement).setPointerCapture(event.pointerId); fromPointer(event); }} onPointerMove={(event) => drag.current && fromPointer(event)} onPointerUp={() => (drag.current = false)} onPointerCancel={() => (drag.current = false)}>
<style>{CSS}</style>
<div className="gcdcm-layer">{before}</div>
<div className="gcdcm-layer gcdcm-after">{after}</div>
<span className="gcdcm-tag" style={{ left: 14 }}>{beforeLabel}</span>
<span className="gcdcm-tag" style={{ right: 14 }}>{afterLabel}</span>
<span className="gcdcm-line" />
<button className="gcdcm-handle" type="button" role="slider" aria-label="Comparar antes y después" aria-valuemin={0} aria-valuemax={100} aria-valuenow={Math.round(x)} aria-valuetext={`${Math.round(x)}% ${beforeLabel}`} onKeyDown={key}>
<svg width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.4" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true"><path d="m9 7-5 5 5 5M15 7l5 5-5 5" /></svg>
</button>
</div>
);
}
Úsalo en tu proyecto
Instálalo con la CLI de shadcn.
npx shadcn@latest add https://www.gassierconsulting.com/r/datos-comparadorEjemplo de uso de Comparador antes y después
Después de copiar datos-comparador.tsx a tu proyecto, impórtalo y colócalo donde lo necesites.
import { DatosComparador } from "./datos-comparador";
export default function Ejemplo() {
return <DatosComparador beforeLabel="Ejemplo" />;
}Propiedades de DatosComparador
DatosComparador acepta 7 propiedades: todas son opcionales y tienen un valor por defecto, así que funciona sin configurar nada.
| Propiedad | Tipo | Descripción |
|---|---|---|
before? | ReactNode | Opcional. |
after? | ReactNode | Opcional. |
beforeLabel? | string | Opcional. |
afterLabel? | string | Opcional. |
defaultValue? | number | Opcional. |
className? | string | Opcional. |
style? | CSSProperties | Opcional. |
Accesibilidad y rendimiento
El archivo tiene 83 líneas (5 KB) y no necesita @keyframes. Esto es lo que hace Comparador antes y después por quien lo usa:
- Detecta prefers-reduced-motion y baja o quita el movimiento cuando la persona lo pide.
- Muestra un anillo de foco visible al navegar con teclado (:focus-visible).
- Declara roles ARIA para lectores de pantalla: slider.
- Responde al teclado, no solo al ratón.
- Reacciona al puntero con eventos pointer (ratón, lápiz y táctil).
- Es un componente de cliente de Next.js: incluye la directiva "use client".