Debian Codegraph @

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

raw
1 import { useReducer, useState } from 'react';
2 import { NumberInput, ValidatedOptions } from '@patternfly/react-core';
3
4 export const NumberInputWithStatus: React.FunctionComponent = () => {
5 const max = 10;
6 const min = 0;
7
8 const [validated, setValidated] = useState<ValidatedOptions>(ValidatedOptions.success);
9 const [value, setValue] = useReducer((state, newVal) => Math.max(min, Math.min(max, Number(newVal))), 5);
10
11 const onPlus = () => {
12 const newVal = (value || 0) + 1;
13 setValue(newVal);
14 validate(newVal);
15 };
16
17 const onMinus = () => {
18 const newVal = (value || 0) - 1;
19 setValue(newVal);
20 validate(newVal);
21 };
22
23 const onChange = (event: React.FormEvent<HTMLInputElement>) => {
24 const value = (event.target as HTMLInputElement).value;
25 setValue(value === '' ? value : +value);
26 validate(value);
27 };
28
29 const validate = (newVal) => {
30 const diff = Math.abs(5 - newVal);
31 if (diff > 3) {
32 setValidated(ValidatedOptions.error);
33 } else if (diff > 1) {
34 setValidated(ValidatedOptions.warning);
35 } else {
36 setValidated(ValidatedOptions.success);
37 }
38 };
39 return (
40 <>
41 In the following example, the validated status will update based on the value of the number input and how far from
42 the number 5 it is.
43 <br />
44 <NumberInput
45 validated={validated}
46 value={value}
47 min={0}
48 max={10}
49 onMinus={onMinus}
50 onPlus={onPlus}
51 onChange={onChange}
52 inputName="input"
53 inputAriaLabel="number input"
54 minusBtnAriaLabel="minus"
55 plusBtnAriaLabel="plus"
56 />
57 </>
58 );
59 };