Skip to content

Commit

Permalink
[NumberInput][base-ui] Warn when changing control mode with `useContr…
Browse files Browse the repository at this point in the history
…olled` (#38757)
  • Loading branch information
sai6855 authored Sep 14, 2023
1 parent 41bdcb7 commit d4c308a
Show file tree
Hide file tree
Showing 2 changed files with 49 additions and 2 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -270,4 +270,42 @@ describe('useNumberInput', () => {
expect(handleChange.args[0][1]).to.equal(undefined);
});
});

describe('warnings', () => {
it('should warn when switching from uncontrolled to controlled', () => {
const handleChange = spy();
function NumberInput({ value }: { value?: number }) {
const { getInputProps } = useNumberInput({
onChange: handleChange,
value,
});

return <input {...getInputProps()} />;
}
const { setProps } = render(<NumberInput />);
expect(() => {
setProps({ value: 5 });
}).to.toErrorDev(
'MUI: A component is changing the uncontrolled value state of NumberInput to be controlled',
);
});

it('should warn when switching from controlled to uncontrolled', () => {
const handleChange = spy();
function NumberInput({ value }: { value?: number }) {
const { getInputProps } = useNumberInput({
onChange: handleChange,
value,
});

return <input {...getInputProps()} />;
}
const { setProps } = render(<NumberInput value={5} />);
expect(() => {
setProps({ value: undefined });
}).to.toErrorDev(
'MUI: A component is changing the controlled value state of NumberInput to be uncontrolled',
);
});
});
});
13 changes: 11 additions & 2 deletions packages/mui-base/src/unstable_useNumberInput/useNumberInput.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,11 @@
'use client';
import * as React from 'react';
import MuiError from '@mui/utils/macros/MuiError.macro';
import { unstable_useForkRef as useForkRef, unstable_useId as useId } from '@mui/utils';
import {
unstable_useForkRef as useForkRef,
unstable_useId as useId,
unstable_useControlled as useControlled,
} from '@mui/utils';
import { FormControlState, useFormControlContext } from '../FormControl';
import {
UseNumberInputParameters,
Expand Down Expand Up @@ -81,7 +85,12 @@ export function useNumberInput(parameters: UseNumberInputParameters): UseNumberI
const [focused, setFocused] = React.useState(false);

// the "final" value
const [value, setValue] = React.useState(valueProp ?? defaultValueProp);
const [value, setValue] = useControlled({
controlled: valueProp,
default: defaultValueProp,
name: 'NumberInput',
});

// the (potentially) dirty or invalid input value
const [dirtyValue, setDirtyValue] = React.useState<string | undefined>(
value ? String(value) : undefined,
Expand Down

0 comments on commit d4c308a

Please sign in to comment.