Skip to content

Commit

Permalink
[added] CustomPropTypes.singlePropFrom
Browse files Browse the repository at this point in the history
Throw an error if multiple properties in the given list have a value
  • Loading branch information
aabenoja committed May 26, 2015
1 parent 4e3a15f commit 2749cfd
Show file tree
Hide file tree
Showing 2 changed files with 49 additions and 1 deletion.
30 changes: 29 additions & 1 deletion src/utils/CustomPropTypes.js
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,17 @@ let CustomPropTypes = {
* @param componentName
* @returns {Error|undefined}
*/
keyOf: createKeyOfChecker
keyOf: createKeyOfChecker,
/**
* Checks if only one of the listed properties is in use. An error is given
* if multiple have a value
*
* @param props
* @param propName
* @param componentName
* @returns {Error|undefined}
*/
singlePropFrom: createSinglePropFromChecker
};

/**
Expand Down Expand Up @@ -80,4 +90,22 @@ function createKeyOfChecker(obj) {
return createChainableTypeChecker(validate);
}

function createSinglePropFromChecker(arrOfProps) {
function validate(props, propName, componentName) {
const usedPropCount = arrOfProps
.map(listedProp => props[listedProp])
.reduce((acc, curr) => acc + (curr !== undefined ? 1 : 0), 0);

if (usedPropCount > 1) {
const [first, ...others] = arrOfProps;
const message = `${others.join(', ')} and ${first}`;
return new Error(
`Invalid prop '${propName}', only one of the following ` +
`may be provided: ${message}`
);
}
}
return validate;
}

export default CustomPropTypes;
20 changes: 20 additions & 0 deletions test/CustomPropTypesSpec.js
Original file line number Diff line number Diff line change
Expand Up @@ -47,4 +47,24 @@ describe('CustomPropTypes', function () {
assert.isUndefined(validate('bar'));
});
});

describe('singlePropFrom', function () {
function validate(testProps) {
const propList = ['children', 'value'];

return CustomPropTypes.singlePropFrom(propList)(testProps, 'value', 'Component');
}

it('Should return undefined if only one listed prop in used', function () {
const testProps = {value: 5};

assert.isUndefined(validate(testProps));
});

it('Should return error if multiple of the listed properties have values', function () {
const testProps = {value: 5, children: 5};

validate(testProps).should.be.instanceOf(Error);
});
});
});

0 comments on commit 2749cfd

Please sign in to comment.