Search code examples
reactjsreact-proptypes

Is there a prop that can be used to ignore missing mandatory proptypes warnings?


I know this question may seems a little strange but I am trying to implement a skeleton loader. To do so, I would like to send my components a prop like "loading={true}" to tell them to ignore the others arguments as they won't need it (they only need to show they're loading, not to show anything meaningful)

I thought of a few workarounds :

  • I could declare the proptypes as not required and simply declare a default value ... But then I wouldn't have any warning outside the loading step
  • Just give some jumbo props for the mandatory props but that's a lot of useless code
  • Duplicate every component - the "standard one" and the "loading one" but I have some rare corner cases where an element decide how many elements they show in javascript - based on the user's viewport that has to be duplicated too - alongside with doubling the files' volume for a loader.

This last idea seems the most promising as it would also prevent encumbering the components with additional conditions but I still would like to study the idea of letting the component manage their own render.

So, is there a way of telling Proptypes "hey, I know you don't have all the required props but trust me this one time but not the other times ?"

Many thanks in advance !


Solution

  • You could use an optional shape.

    It could look something like this; (consider as pseudo code)

    import React from 'react';
    import PropTypes from 'prop-types';
    import MyComponent from 'somewhere';
    
    const Example = ({ loading, options }) => (
      loading ? <div>Loading...</div> : <MyComponent {...options} />
    );
    
    Example.propTypes = {
      loading: PropTypes.bool.isRequired,
      options: PropTypes.oneOfType([null, PropTypes.shape({
        prop1: PropTypes.bool.isRequired,
      })]),
    }
    
    Example.defaultProps = {
      options: null,
    }
    
    export default Example;