Skip to content

Commit

Permalink
[Autocomplete] Add verbose warning for defaultValue (#27925)
Browse files Browse the repository at this point in the history
  • Loading branch information
vedadeepta committed Aug 24, 2021
1 parent 7bdf8a3 commit af74554
Show file tree
Hide file tree
Showing 3 changed files with 28 additions and 2 deletions.
5 changes: 4 additions & 1 deletion docs/pages/api-docs/autocomplete.json
Expand Up @@ -20,7 +20,10 @@
"clearText": { "type": { "name": "string" }, "default": "'Clear'" },
"closeText": { "type": { "name": "string" }, "default": "'Close'" },
"componentsProps": { "type": { "name": "object" }, "default": "{}" },
"defaultValue": { "type": { "name": "any" }, "default": "props.multiple ? [] : null" },
"defaultValue": {
"type": { "name": "custom", "description": "any" },
"default": "props.multiple ? [] : null"
},
"disableClearable": { "type": { "name": "bool" } },
"disableCloseOnSelect": { "type": { "name": "bool" } },
"disabled": { "type": { "name": "bool" } },
Expand Down
12 changes: 11 additions & 1 deletion packages/material-ui/src/Autocomplete/Autocomplete.js
Expand Up @@ -718,7 +718,17 @@ Autocomplete.propTypes /* remove-proptypes */ = {
* The default value. Use when the component is not controlled.
* @default props.multiple ? [] : null
*/
defaultValue: PropTypes.any,
defaultValue: chainPropTypes(PropTypes.any, (props) => {
if (props.multiple && props.defaultValue !== undefined && !Array.isArray(props.defaultValue)) {
return new Error(
[
'Material-UI: The Autocomplete expects the `defaultValue` prop to be an array when `multiple={true}` or undefined.',
`However, ${props.defaultValue} was provided.`,
].join('\n'),
);
}
return null;
}),
/**
* If `true`, the input can't be cleared.
* @default false
Expand Down
13 changes: 13 additions & 0 deletions packages/material-ui/src/Autocomplete/Autocomplete.test.js
Expand Up @@ -1342,6 +1342,19 @@ describe('<Autocomplete />', () => {
);
}).toErrorDev('The Autocomplete expects the `value` prop to be an array or undefined.');
});

it('warn if the type of the defaultValue is wrong', () => {
expect(() => {
PropTypes.checkPropTypes(
Autocomplete.propTypes,
{ multiple: true, defaultValue: 'wrong-string', options: [], renderInput: () => null },
'prop',
'Autocomplete',
);
}).toErrorDev(
'The Autocomplete expects the `defaultValue` prop to be an array when `multiple={true}` or undefined.',
);
});
});

describe('prop: options', () => {
Expand Down

0 comments on commit af74554

Please sign in to comment.