Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Accessing all props in nested propTypes in a React component

Tags:

reactjs

I am trying to conditionally make lightboxImage required or not based on the property of disableLightbox. However when i read props from lightboxImage I only get the first level of properties (src, width, height, aspectRatio) and not the level up (photos, disableLightbox). Is there any way I can read all of the properties?

Gallery.propTypes = {
    photos: React.PropTypes.arrayOf(
        React.PropTypes.shape({
            src: React.PropTypes.string.isRequired, 
            width: React.PropTypes.number.isRequired,
            height: React.PropTypes.number.isRequired,
            aspectRatio: React.PropTypes.number.isRequired,
            lightboxImage: props => console.log(props)
        })  
    ).isRequired,
    disableLightbox: React.PropTypes.bool
};     
like image 389
neptunian Avatar asked Mar 13 '23 13:03

neptunian


1 Answers

@MatthewHerbst Explained the key idea, a custom validator, but here's a rewritten version of the example code that's more complete and applicable and yet simpler (FYI, untested though):

photos: function (props, propName, componentName) {
  // I don't know what `lightboxImage` is, I'll assume string.
  var lightboxImageValidator = React.PropTypes.string;
  if (!props.disableLightbox) {
    lightboxImageValidator = lightboxImageValidator.isRequired;
  }

  return React.PropTypes.arrayOf(
    React.PropTypes.shape({
      src: React.PropTypes.string.isRequired, 
      width: React.PropTypes.number.isRequired,
      height: React.PropTypes.number.isRequired,
      aspectRatio: React.PropTypes.number.isRequired,
      lightboxImage: lightboxImageValidator,
    })  
  ).isRequired.apply(this, arguments);
}
like image 140
JMM Avatar answered Mar 16 '23 04:03

JMM