Skip to content

Commit

Permalink
fix(NumberInput): restore defaultValue prop functionality in uncont…
Browse files Browse the repository at this point in the history
…rolled number input (#7312)

* test(NumberInput): add uncontrolled input defaultValue test

* fix(NumberInput): avoid spreading defaultValue into input

* fix(NumberInput): add defaultValue typecheck

* fix(NumberInput): remove default internal state value in gDSFP

Co-authored-by: kodiakhq[bot] <49736102+kodiakhq[bot]@users.noreply.github.com>
  • Loading branch information
emyarod and kodiakhq[bot] committed Nov 18, 2020
1 parent cb74016 commit 656e084
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 2 deletions.
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

0 comments on commit 656e084

Please sign in to comment.