Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix(NumberInput): restore defaultValue prop functionality in uncontrolled number input #7312

Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 18 additions & 0 deletions packages/react/src/components/NumberInput/NumberInput-test.js
Original file line number Diff line number Diff line change
Expand Up @@ -155,6 +155,24 @@ describe('NumberInput', () => {
);
const getNumberInput = (wrapper) => wrapper.find('input');

it('should correctly set defaultValue on uncontrolled input', () => {
const wrapper = mount(
<NumberInput
min={-1}
max={100}
defaultValue={10}
id="test"
label="Number Input"
className="extra-class"
/>
);
const numberInput = getNumberInput(wrapper);
expect(wrapper.find('NumberInput').instance().state.value).toEqual(
10
);
expect(numberInput.prop('value')).toEqual(10);
});

it('should set value as expected when value > min', () => {
const wrapper = getWrapper(-1, 100, 0);
const numberInput = getNumberInput(wrapper);
Expand Down
8 changes: 6 additions & 2 deletions packages/react/src/components/NumberInput/NumberInput.js
Original file line number Diff line number Diff line change
Expand Up @@ -170,7 +170,7 @@ class NumberInput extends Component {
translateWithId: (id) => defaultTranslations[id],
};

static getDerivedStateFromProps({ min, max, value = 0 }, state) {
static getDerivedStateFromProps({ min, max, value }, state) {
const { prevValue } = state;

if (useControlledStateWithValue && value === '' && prevValue !== '') {
Expand Down Expand Up @@ -204,7 +204,10 @@ class NumberInput extends Component {
this.state = {};
return;
}
let value = useControlledStateWithValue ? props.defaultValue : props.value;
let value =
useControlledStateWithValue || typeof props.defaultValue !== 'undefined'
? props.defaultValue
: props.value;
value = value === undefined ? 0 : value;
if (props.min || props.min === 0) {
value = Math.max(props.min, value);
Expand Down Expand Up @@ -300,6 +303,7 @@ class NumberInput extends Component {
translateWithId: t,
isMobile,
size,
defaultValue, // eslint-disable-line
...other
} = this.props;

Expand Down