ljharb / prop-types-tools

Custom React PropType validators
MIT License
671 stars 50 forks source link

add requiredBy validator #30

Closed sdjidjev closed 7 years ago

sdjidjev commented 7 years ago

requiredBy: pass in a prop name and propType, and require that the prop is defined and is not its default value if the passed in prop name is truthy. if the default value is not provided, defaults to checking against null.

Example:

const onFooButtonPressDefault = () => {};
const propTypes = {
  fooButtonText: requiredBy('showFoo', PropTypes.string),
  onFooButtonPress: requiredBy('showFoo', PropTypes.func, onFooButtonPressDefault),
  showFooButton: PropTypes.bool,
};

const defaultProps = {
  fooButtonText: null,
  onFooButtonPress: onFooButtonPressDefault,
  showFooButton: false,
};

Passes validator

<MyComponent
  fooButtonText="text"
  onFooButtonPress={this.handleFooButtonPress}
  showFooButton
/>

Does not pass validator

<MyComponent
  fooButtonText={4}
  onFooButtonPress={this.handleFooButtonPress}
  showFooButton
/>
<MyComponent
  onFooButtonPress={this.handleFooButtonPress}
  showFooButton
/>
<MyComponent
  fooButtonText="text"
  showFooButton
/>
<MyComponent showFooButton />
ljharb commented 7 years ago

hm - not sure why coverage is failing here exactly. let me take a look

sdjidjev commented 7 years ago

that's quite the high expectation!

ERROR: Coverage for branches (98.98%) does not meet global threshold (99%)
ljharb commented 7 years ago

:-D I'm actually about to push a branch that gets it to 100%, which will avoid what's happening here, which is that your addition is increasing the denominator such that the branches percentage falls from 99 to 98, even tho your addition is 100% covered. I'll rebase yours after that's done.

ljharb commented 7 years ago

k, rebased your branch (and added a commit that fixes using NaN as the defaultValue). Once tests pass, this should be good to go!

ljharb commented 7 years ago

Thanks!