Skip to content

Commit 3646d8a

Browse files
fix: NumberInput react controlled vs uncontrolled handling (#22139)
* fix: number input react controlled vs uncontrolled handling * refactor: move tests to respective controlled and uncontrolled blocks * chore: add todo for re-organizing stories for better clarity * fix: ai-label story --------- Co-authored-by: Heloise Lui <71858203+heloiselui@users.noreply.github.com>
1 parent fe9a329 commit 3646d8a

3 files changed

Lines changed: 1986 additions & 1586 deletions

File tree

packages/react/src/components/NumberInput/NumberInput.stories.js

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -55,6 +55,7 @@ const reusableProps = {
5555
max: 100000000,
5656
};
5757

58+
// TODO: Potential opportunity to differentiate between controlled and uncontrolled stories
5859
export const Default = (args) => {
5960
const [value, setValue] = React.useState(50);
6061

@@ -127,7 +128,7 @@ export const withAILabel = (args) => {
127128
<NumberInput
128129
min={reusableProps.min}
129130
max={reusableProps.max}
130-
value={50}
131+
defaultValue={50}
131132
label="NumberInput label"
132133
helperText="Optional helper text."
133134
invalidText="Number is not valid"

packages/react/src/components/NumberInput/NumberInput.tsx

Lines changed: 9 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -749,7 +749,11 @@ const NumberInput = React.forwardRef<HTMLInputElement, NumberInputProps>(
749749
: Number(event.target.value),
750750
direction: value < event.target.value ? 'up' : 'down',
751751
};
752-
setValue(state.value);
752+
753+
// Only update internal state if component is uncontrolled
754+
if (controlledValue === undefined) {
755+
setValue(state.value);
756+
}
753757

754758
if (onChange) {
755759
onChange(event, state);
@@ -833,7 +837,10 @@ const NumberInput = React.forwardRef<HTMLInputElement, NumberInputProps>(
833837
};
834838

835839
if (type === 'number') {
836-
setValue(state.value);
840+
// Only update internal state if component is uncontrolled
841+
if (controlledValue === undefined) {
842+
setValue(state.value);
843+
}
837844
}
838845

839846
if (type === 'text') {

0 commit comments

Comments
 (0)