Control de cantidad
Stepper numérico con entrada directa, límites mínimo y máximo y botones que se desactivan al llegar al límite.
De 1 a 20 integrantes.
Código completo
Es exactamente el archivo que se descarga. Cópialo a tu proyecto y úsalo.
"use client";
import { useState, useId, type CSSProperties } from "react";
/** Control de cantidad. React + TypeScript, sin dependencias. Personaliza con variables --gcxq-*. */
export type ControlCantidadProps = {
label?: string;
initial?: number;
min?: number;
max?: number;
onChange?: (value: number) => void;
className?: string;
style?: CSSProperties;
};
const CSS = `
.gcxq-root { box-sizing: border-box; min-width: 0; max-width: 100%; color: var(--gcxq-fg, #202421); font: 400 15px/1.5 ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif; }
.gcxq-root *, .gcxq-root *::before, .gcxq-root *::after { box-sizing: border-box; }
.gcxq-root button, .gcxq-root input, .gcxq-root textarea, .gcxq-root select { font: inherit; }
.gcxq-root button, .gcxq-root a { -webkit-tap-highlight-color: transparent; }
.gcxq-root :focus-visible { outline: 2px solid var(--gcxq-accent, #25724b); outline-offset: 4px; }
.gcxq-root ::selection { background: var(--gcxq-accent, #25724b); color: #fff; }
.gcxq-root button:disabled { opacity: .5; cursor: not-allowed; }
.gcxq-root svg { flex-shrink: 0; }
@media (prefers-reduced-motion: reduce) { .gcxq-root *, .gcxq-root *::before, .gcxq-root *::after { animation: none !important; transition-duration: .01ms !important; scroll-behavior: auto !important; } }
.gcxq-root { width: 280px; text-align: center; }
.gcxq-root label { display: block; margin-bottom: 18px; font-weight: 600; }
.gcxq-control { display: flex; align-items: center; gap: 12px; justify-content: center; }
.gcxq-control button { display: grid; place-items: center; width: 48px; height: 48px; border: 1px solid #c5ccc6; border-radius: 50%; color: #334434; background: #fff; cursor: pointer; transition: background .2s; }
.gcxq-control button:hover:not(:disabled) { background: #e2eae2; }
.gcxq-control input { width: 70px; border: 0; background: transparent; color: #202421; text-align: center; font-size: 36px; font-weight: 600; font-variant-numeric: tabular-nums; appearance: textfield; }
.gcxq-control input::-webkit-inner-spin-button { appearance: none; }
.gcxq-root p { color: #59675b; font-size: 12px; margin-top: 18px; }`;
export function ControlCantidad({
label = "Integrantes del equipo",
initial = 3,
min = 1,
max = 20,
onChange,
className = "",
style,
}: ControlCantidadProps) {
const lower = Math.min(min, max);
const upper = Math.max(min, max);
const [value, setValue] = useState(Math.min(upper, Math.max(lower, initial)));
const id = useId();
function change(next: number) {
const bounded = Math.min(
upper,
Math.max(lower, Number.isFinite(next) ? next : lower),
);
setValue(bounded);
onChange?.(bounded);
}
return (
<div className={`gcxq-root ${className}`} style={style}>
<style>{CSS}</style>
<label htmlFor={id}>{label}</label>
<div className="gcxq-control">
<button
type="button"
aria-label="Reducir cantidad"
disabled={value <= lower}
onClick={() => change(value - 1)}
>
<svg
width="18"
height="18"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
strokeWidth="1.8"
aria-hidden="true"
>
<path d="M5 12h14" />
</svg>
</button>
<input
id={id}
type="number"
min={lower}
max={upper}
value={value}
onChange={(e) => change(e.target.valueAsNumber)}
/>
<button
type="button"
aria-label="Aumentar cantidad"
disabled={value >= upper}
onClick={() => change(value + 1)}
>
<svg
width="18"
height="18"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
strokeWidth="1.8"
aria-hidden="true"
>
<path d="M5 12h14M12 5v14" />
</svg>
</button>
</div>
<p>
De {lower} a {upper} integrantes.
</p>
</div>
);
}
Úsalo en tu proyecto
Instálalo con la CLI de shadcn.
npx shadcn@latest add https://www.gassierconsulting.com/r/control-cantidadEjemplo de uso de Control de cantidad
Después de copiar control-cantidad.tsx a tu proyecto, impórtalo y colócalo donde lo necesites.
import { ControlCantidad } from "./control-cantidad";
export default function Ejemplo() {
return <ControlCantidad label="Ejemplo" />;
}Propiedades de ControlCantidad
ControlCantidad acepta 7 propiedades: todas son opcionales y tienen un valor por defecto, así que funciona sin configurar nada.
| Propiedad | Tipo | Descripción |
|---|---|---|
label? | string | Opcional. |
initial? | number | Opcional. |
min? | number | Opcional. |
max? | number | Opcional. |
onChange? | (value: number) => void | Opcional. |
className? | string | Opcional. |
style? | CSSProperties | Opcional. |
Personaliza Control de cantidad con variables CSS
Define estas variables en el contenedor o en tu hoja de estilos para cambiar los colores sin tocar el componente. Si no las defines, se usa el valor por defecto.
| Variable | Valor por defecto |
|---|---|
--gcxq-fg | #202421 |
--gcxq-accent | #25724b |
Accesibilidad y rendimiento
El archivo tiene 112 líneas (4 KB) y no necesita @keyframes. Esto es lo que hace Control de cantidad 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).
- Expone su estado a tecnologías de apoyo con atributos aria-*.
- Es un componente de cliente de Next.js: incluye la directiva "use client".