reactjsreact-proptypes

How to add propTypes to an unnamed component?


I want to provide propTypes for a component that is computed in real time.

Consider the following code:

const Comp = (a, b, c) => (d) => {
    const e = computeABCD(a, b, c, d);
    return <E e={e} />
}

Comp.propTypes = {
   a: PropTypes.string.isRequired,
   b: PropTypes.string.isRequired,
   c: PropTypes.string.isRequired,
}

How can I add propTypes to the component that is returned by Comp?

The only way I can think of doing this is creating a named component within the function Comp and setting the PropTypes in there.

Would that be a idiomatic solution?


Solution

  • At least you have to write the component definition somewhere to return. There you can write the proptypes.

    const Comp = (a, b, c) => (d) => {
        const e = computeABCD(a, b, c, d);
        return <E e={e} />
    }
    
    Comp.propTypes = {
       a: PropTypes.string.isRequired,
       b: PropTypes.string.isRequired,
       c: PropTypes.string.isRequired,
    }
    
    const E = ({e}) => {
    }
    
    E.propTypes = {
     e: PropTypes.string
    }