Debian Codegraph @

node/@patternfly/react-core/src/components/NumberInput/examples/NumberInputCustomStepAndThreshold.tsx

raw
1 import { useState } from 'react';
2 import { NumberInput } from '@patternfly/react-core';
3
4 export const NumberInputCustomStepAndThreshold: React.FunctionComponent = () => {
5 const [value, setValue] = useState<number | ''>(90);
6 const minValue = 90;
7 const maxValue = 100;
8 const step = 3;
9
10 const normalizeBetween = (value, min, max) => {
11 if (min !== undefined && max !== undefined) {
12 return Math.max(Math.min(value, max), min);
13 } else if (value <= min) {
14 return min;
15 } else if (value >= max) {
16 return max;
17 }
18 return value;
19 };
20
21 const stepper = (stepValue: number) => {
22 setValue((value || 0) + stepValue);
23 };
24
25 const onChange = (event: React.FormEvent<HTMLInputElement>) => {
26 const value = (event.target as HTMLInputElement).value;
27 setValue(value === '' ? value : +value);
28 };
29
30 const onBlur = (event: React.FormEvent<HTMLInputElement>) => {
31 const target = event.target as HTMLInputElement;
32 const newValue = normalizeBetween(isNaN(+target.value) ? 0 : Number(target.value), minValue, maxValue);
33 setValue(newValue);
34 };
35
36 return (
37 <NumberInput
38 value={value}
39 min={minValue}
40 max={maxValue}
41 onMinus={() => stepper(-step)}
42 onChange={onChange}
43 onBlur={onBlur}
44 onPlus={() => stepper(step)}
45 inputName="input"
46 inputAriaLabel="number input"
47 minusBtnAriaLabel="minus"
48 plusBtnAriaLabel="plus"
49 />
50 );
51 };