Skip to content

Commit

Permalink
Improve PropTypes.oneOf warning for non-primitive values
Browse files Browse the repository at this point in the history
The improvement was suggested in facebook#1919.
  • Loading branch information
shuaibiyy committed Nov 30, 2015
1 parent 34fbcf2 commit 7636365
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 1 deletion.
13 changes: 12 additions & 1 deletion src/isomorphic/classic/types/ReactPropTypes.js
Original file line number Diff line number Diff line change
Expand Up @@ -217,13 +217,24 @@ function createEnumTypeChecker(expectedValues) {

function validate(props, propName, componentName, location, propFullName) {
var propValue = props[propName];
var locationName = ReactPropTypeLocationNames[location];

for (var i = 0; i < expectedValues.length; i++) {
if (expectedValues[i] !== null &&
(typeof expectedValues[i] === 'object' || typeof expectedValues[i] === 'function')
) {
return new Error(
`Invalid ${locationName} \`${propFullName}\` of value \`${propValue}\` ` +
`supplied to \`${componentName}\`, \`oneOf\` expects an enum of primitive values. ` +
`Did you mean to use \`oneOfType\`?`
);
}

if (propValue === expectedValues[i]) {
return null;
}
}

var locationName = ReactPropTypeLocationNames[location];
var valuesString = JSON.stringify(expectedValues);
return new Error(
`Invalid ${locationName} \`${propFullName}\` of value \`${propValue}\` ` +
Expand Down
12 changes: 12 additions & 0 deletions src/isomorphic/classic/types/__tests__/ReactPropTypes-test.js
Original file line number Diff line number Diff line change
Expand Up @@ -601,6 +601,18 @@ describe('ReactPropTypes', function() {
'Invalid prop `testProp` of value `false` supplied to ' +
'`testComponent`, expected one of [0,"false"].'
);
typeCheckFail(
PropTypes.oneOf(['red', 'blue']),
{},
'Invalid prop `testProp` of value `[object Object]` supplied to ' +
'`testComponent`, expected one of ["red","blue"].'
);
typeCheckFail(
PropTypes.oneOf(['red', 'blue']),
PropTypes.string,
'Invalid prop `testProp` of value `function () { [native code] }` supplied to ' +
'`testComponent`, expected one of ["red","blue"].'
);
});

it('should not warn for valid values', function() {
Expand Down

0 comments on commit 7636365

Please sign in to comment.