ljharb / prop-types-tools

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

Is it possible to validate all children have a prop? #61

Closed Asday closed 4 years ago

Asday commented 5 years ago

Why does there exist a rather complex prop-type that checks three conditions, without those conditions being individually available, while and exists?

If there's not a reason, might I open a PR?

ljharb commented 5 years ago

Because we didn’t have a use case for anything but the complete check.

What’s your use case?

Asday commented 5 years ago

Might be silly? Hopefully you'll be able to tell me.

Writing a <Wizard /> that expects to be passed children with a unique (to the wizard) stepName prop. Currently my thinking is and([childrenHaveProp('stepName'), childrenPropsAreUnique('stepName')]) or something similar would be elegant.

ljharb commented 5 years ago

so <div stepName="not a real step" /> would be valid?

Asday commented 5 years ago

I don't see why not. That sort of functionality would be useful for showing an interstitial page like YouGov's "on to a different topic..." pages in their surveys.

ljharb commented 5 years ago

Can you use childrenOf(withShape(PropTypes.element, { stepName: string.isRequired })).isRequired?

Asday commented 5 years ago

Ooh, that looks very promising. So that's essentially the childrenHaveProp() in my conjectural example I think?

Is the .isRequired on childrenOf() making it so at least one is required?

ljharb commented 5 years ago

yep, exactly.

Asday commented 5 years ago

Well gosh I think that's that then.

I feel like this issue kinda took a walk away from what I was originally askin', 'cause I was asking the wrong thing. I still think it's appropriate to close though, as my issue has been solved, so I bid you adieu, and thanks.

Asday commented 5 years ago

Sorry, I'm back - that doesn't appear to work. As a cut down example:

class Wizard extends Component {
  static propTypes = {
    children: childrenOf(withShape(
      PropTypes.element,
      { stepName: PropTypes.string.isRequired },
    )).isRequired,
  }

  render = () => null
}

<Wizard><Text stepName="First">First</Text><Text stepName="Last">Last</Text></Wizard> raises Warning: Failed prop type: The propstepNameis marked as required inWizard, but its value isundefined`. Dropping thestepName` prop from either or both of the children results in the same message.

It looks like prop-types (facebook's, not yours) is checking for stepName on <Wizard /> rather than its children, but I'm not smart enough to figure out if that's true, and/or why.

I've renamed the issue to make more sense given the direction it took.

ljharb commented 5 years ago

@Asday with the latest version of prop-types (facebook's), is this still an issue?

ljharb commented 4 years ago

Closing pending confirmation.