| 1 |
import { Fragment, useState } from 'react'; |
| 2 |
import { NumberInput } from '@patternfly/react-core'; |
| 3 |
|
| 4 |
export const NumberInputUnitThreshold: React.FunctionComponent = () => { |
| 5 |
const [value, setValue] = useState<number | ''>(0); |
| 6 |
const minValue = 0; |
| 7 |
const maxValue = 10; |
| 8 |
|
| 9 |
const normalizeBetween = (value, min, max) => { |
| 10 |
if (min !== undefined && max !== undefined) { |
| 11 |
return Math.max(Math.min(value, max), min); |
| 12 |
} else if (value <= min) { |
| 13 |
return min; |
| 14 |
} else if (value >= max) { |
| 15 |
return max; |
| 16 |
} |
| 17 |
return value; |
| 18 |
}; |
| 19 |
|
| 20 |
const onMinus = () => { |
| 21 |
const newValue = normalizeBetween((value as number) - 1, minValue, maxValue); |
| 22 |
setValue(newValue); |
| 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.FocusEvent<HTMLInputElement>) => { |
| 31 |
const blurVal = +event.target.value; |
| 32 |
|
| 33 |
if (blurVal < minValue) { |
| 34 |
setValue(minValue); |
| 35 |
} else if (blurVal > maxValue) { |
| 36 |
setValue(maxValue); |
| 37 |
} |
| 38 |
}; |
| 39 |
|
| 40 |
const onPlus = () => { |
| 41 |
const newValue = normalizeBetween((value as number) + 1, minValue, maxValue); |
| 42 |
setValue(newValue); |
| 43 |
}; |
| 44 |
|
| 45 |
return ( |
| 46 |
<Fragment> |
| 47 |
With a minimum value of 0 and maximum value of 10 |
| 48 |
<br /> |
| 49 |
<NumberInput |
| 50 |
value={value} |
| 51 |
min={minValue} |
| 52 |
max={maxValue} |
| 53 |
onMinus={onMinus} |
| 54 |
onChange={onChange} |
| 55 |
onBlur={onBlur} |
| 56 |
onPlus={onPlus} |
| 57 |
inputName="input" |
| 58 |
inputAriaLabel="number input" |
| 59 |
minusBtnAriaLabel="minus" |
| 60 |
plusBtnAriaLabel="plus" |
| 61 |
unit="%" |
| 62 |
/> |
| 63 |
</Fragment> |
| 64 |
); |
| 65 |
}; |