reactjsreact-proptypes

How do I validate props for a component within a component in React?


I have been going through my application and adding prop validations using SonarLint to validate my work and all has been fine so far. But I need to validate a component nested in the main component and can't figure out how to structure it properly.

My component:

import PropTypes from 'prop-types';

export const Parent1 = () => {
    ...

    const ChildOfParent1 = ({ data }) => {
        ...
    }
}

const Parent2 = ({ value, onFuction }) => {
    ...
}

and my PropTypes validation I've been doing:

Parent2.propTypes = {
    value: PropTypes.object,
    onFuction: PropTypes.func,
}

ChildOfParent1.PropTypes = {
    data: PropTypes.object,
} 

SonarLint doesn't seem to think of ChildOfParent1 as valid as the warnings about props not being validated in ChildOfParent1 still show

I tried doing the following:

Parent1.ChildOfParent1.propTypes = {
    data: PropTypes.object,
}

But then SonarLint says 'data' PropType is defined but prop is never used despite the warnings disappearing in the code.


Solution

  • There is no reason why you need to nest the component inside Parent1

    You can still do this and still achieve what needs to be achieved

    
    const ChildOfParent1 = ({ data }) => {
            ...
    }
    
    export const Parent1 = () => {
        ...
    }
    
    const Parent2 = ({ value, onFuction }) => {
        ...
    }
    

    This way you can do whatever you need to do with your PropTypes.