Skip to content

Commit

Permalink
refactor: added array support for requiredWhen
Browse files Browse the repository at this point in the history
  • Loading branch information
PKulkoRaccoonGang committed Nov 9, 2023
1 parent ddf4b82 commit 8fa7b1a
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 3 deletions.
2 changes: 1 addition & 1 deletion src/Chip/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,7 @@ Use `onClick` prop to make the whole `Chip` clickable, this will also add approp
## With Icon Before and After
### Basic Usage

Use `iconBefore` and `iconAfter` props to provide icons for the `Chip`, note that you also have to provide
Use `iconBefore` and `iconAfter` props to provide icons for the `Chip`, note that you also can provide
accessible names for these icons for screen reader support via `iconBeforeAlt` and `iconAfterAlt` respectively.

```jsx live
Expand Down
19 changes: 17 additions & 2 deletions src/utils/propTypes/utils.js
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,16 @@ export const customPropTypeRequirement = (targetType, conditionFn, filterString)
}
);

/**
* Checks if all specified properties are defined in the `props` object.
*
* @param {Object} props - The object in which the properties are checked.
* @param {string[]} otherPropNames - An array of strings representing the property names to be checked.
* @returns {boolean} `true` if all properties are defined and not equal to `undefined`, `false` otherwise.
*/
export const isEveryPropDefined = (props, otherPropNames) => otherPropNames
.every(propName => props[propName] !== undefined);

/**
* Returns a PropType entry with the given propType that is required if otherPropName
* is truthy.
Expand All @@ -34,8 +44,13 @@ export const customPropTypeRequirement = (targetType, conditionFn, filterString)
export const requiredWhen = (propType, otherPropName) => (
customPropTypeRequirement(
propType,
(props) => props[otherPropName] === true,
`${otherPropName} is truthy`,
(props) => {
if (Array.isArray(otherPropName)) {
return isEveryPropDefined(props, otherPropName);
}
return props[otherPropName] === true;
},
`${otherPropName} ${Array.isArray(otherPropName) ? 'are defined' : 'is truthy'}`,
)
);

Expand Down

0 comments on commit 8fa7b1a

Please sign in to comment.