UNPKG

react-quantity-input

Version:

A simple, customizable quantity input component for React that allows users to increment/decrement numeric values.

55 lines (48 loc) 2.31 kB
import l from"react";import{useState as I}from"react";import c from"styled-components";var C=c.div` display: flex; align-items: center; justify-content: space-between; `,N=c.input` width: 60px; height: 48px; padding: 8px; font-size: 14px; border: solid 1px #ddd; border-color: ${a=>a.$isInvalid?"red !important":"#ddd"}; outline: none; text-align: center; box-sizing: border-box; z-index: 10; &:focus { box-shadow: 0px 0px 6px 2px rgba(0, 0, 0, 0.12); } &:valid { border-color: #ccc; } &:disabled { opacity: 0.6; cursor: not-allowed; } `,p=c.button` display: flex; justify-content: center; align-items: center; width: 48px; height: 48px; background-color: white; border: solid 1px #ddd; color: #999; font-size: 20px; outline: none; cursor: pointer; transition: background-color 0.16s; border-left: ${a=>a.$type==="INCREMENT"?"0px":""}; border-right: ${a=>a.$type==="DECREASE"?"0px":""}; &:hover { background-color: #efefef; } &:disabled { opacity: 0.6; cursor: not-allowed; } `;function R(a){let{min:r=0,max:i=100,step:b=1,placeholder:m,maxLength:y,disabled:u,isInvalid:f,onState:o}=a,[d,s]=I({quantity:"",decreaseDisabled:!1,incrementDisabled:!1}),g=t=>{let e=t.target.value,D=/^([-]{1})?([0-9.]+)?$/.test(e);e===""&&s({...d,quantity:"",decreaseDisabled:!1,incrementDisabled:!1}),D&&s(v=>({...v,quantity:t.target.value,decreaseDisabled:Number(e)===r,incrementDisabled:Number(e)===i}))},x=t=>{let e=Number(t.target.value),n={quantity:e<r?r:e>i?i:e,decreaseDisabled:e<r,incrementDisabled:e>i};s(n),o&&o(n)},E=()=>{s(t=>{let e=Number(t.quantity)-b;if(e>=r){let n={...t,quantity:e,decreaseDisabled:e===r,incrementDisabled:!1};return o&&o(n),n}return{...t,decreaseDisabled:!0}})},h=()=>{s(t=>{let e=Number(t.quantity)+b;if(e<=i){let n={...t,quantity:e,decreaseDisabled:!1,incrementDisabled:e===i};return o&&o(n),n}return{...t,incrementDisabled:!0}})};return l.createElement(C,null,l.createElement(p,{$type:"DECREASE",onClick:E,disabled:u||d.decreaseDisabled},"-"),l.createElement(N,{$isInvalid:f,value:d.quantity,placeholder:m,onChange:g,onBlur:x,maxLength:y,disabled:u,required:!0}),l.createElement(p,{$type:"INCREMENT",onClick:h,disabled:u||d.incrementDisabled},"+"))}export{R as ReactQuantityInput};