-
Notifications
You must be signed in to change notification settings - Fork 4.8k
/
numeric-input.component.js
86 lines (84 loc) · 2.02 KB
/
numeric-input.component.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
import React from 'react';
import classNames from 'classnames';
import PropTypes from 'prop-types';
import {
TextColor,
TextVariant,
} from '../../../helpers/constants/design-system';
import { DECIMAL_REGEX } from '../../../../shared/constants/tokens';
import { Text } from '../../component-library';
export default function NumericInput({
detailText = '',
value = 0,
onChange,
error = '',
autoFocus = false,
allowDecimals = true,
disabled = false,
dataTestId,
placeholder,
id,
name,
inputRef,
}) {
return (
<div
className={classNames('numeric-input', { 'numeric-input--error': error })}
>
<input
type="number"
value={value}
onKeyDown={(e) => {
if (!allowDecimals && e.key === '.') {
e.preventDefault();
}
}}
onChange={(e) => {
const newValue = e.target.value;
const match = DECIMAL_REGEX.exec(newValue);
if (match?.[1]?.length >= 15) {
return;
}
onChange?.(parseFloat(newValue || 0, 10));
}}
min="0"
autoFocus={autoFocus}
disabled={disabled}
data-testid={dataTestId}
placeholder={placeholder}
id={id}
name={name}
ref={inputRef}
/>
{detailText && (
<Text
color={TextColor.textAlternative}
variant={TextVariant.bodySm}
as="span"
>
{detailText}
</Text>
)}
</div>
);
}
NumericInput.propTypes = {
value: PropTypes.oneOfType([PropTypes.number, PropTypes.string]),
detailText: PropTypes.string,
onChange: PropTypes.func,
error: PropTypes.string,
autoFocus: PropTypes.bool,
allowDecimals: PropTypes.bool,
disabled: PropTypes.bool,
dataTestId: PropTypes.string,
placeholder: PropTypes.string,
/**
* The name of the input
*/
name: PropTypes.string,
/**
* The id of the input element. Should be used with htmlFor with a label element.
*/
id: PropTypes.string,
inputRef: PropTypes.object,
};