Search code examples
reactjsreact-proptypes

PropTypes for functions being passed down


Given the code below, how do I set up proptypes for name,label, and onChange?

My current proptypes don't seem to work.


function FilterCheckbox(props) {
    return (
        <div>
            <FormControlLabel
                control={
                    <Checkbox
                        onChange={props.bpmHandler ? props.bpmHandler : props.genreHandler}
                    />
                }
                name={props.name}
                label={props.label}
            />
            <p>name :{props.name}</p>
        </div>
    )
}

FormControlLabel.PropTypes = {
    control:PropTypes.shape({
        name:PropTypes.number,
        label:PropTypes.string
    })
}

export default FilterCheckbox

Solution

  • In your code as you present it, it seems that FormControlLabel is a component defined somewhere else. So first things first, its prop types should be where the component is defined, and I'm assuming would look something like this:

    FormControlLabel.propTypes = {
      control: PropTypes.element,
      name: PropTypes.string,
      label: PropTypes.string,
    }
    

    Then you have a Checkbox component that too should have its prop types defined where the component itself is defined. They probably look something like this:

    Checkbox.propTypes = {
      onChange: PropTypes.func,
    }
    

    And now, in the file you're presenting, you are defining FilterCheckbox and you want it to receive props suited for both FormControlLabel and Checkbox. So I'd do it like this:

    FilterCheckbox.propTypes = {
      name: FormControlLabel.propTypes.name,
      label: FormControlLabel.propTypes.label,
      bpmHandler: Checkbox.propTypes.onChange,
      genreHandler: Checkbox.propTypes.onChange,
    }
    

    And if you don't have access to the prop types of neither Checkbox nor FormControlLabel (meaning that you can't change the files where they are declared, and where they are declared omitted to add prop types). You can still write prop types for FilterCheckbox based on how you intend to use it anyway:

    FilterCheckbox.propTypes = {
      name: PropTypes.string,
      label: PropTypes.string,
      bpmHandler: PropTypes.func,
      genreHandler: PropTypes.func,
    }
    

    PS: just in case this is another thing that was causing you trouble, it's MyComponent.propTypes and not MyComponent.PropTypes.