Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should I set default react properties to null

Tags:

reactjs

I'm new to react and I'm tying to code as short as possible. We're writing react components with many props. The problem is my colleagues keep filling the code which seems very unnecessary to me. So is it correct to set null to all available values or only use propTypes to define property types? Because I don't see such usage examples and I think it is bad practice.

FormAutonumeric.defaultProps = {
    validationRules: null,
    onBlur: null,
    onFocus: null,
    inputClasses: null,
    showErrors: false,
    numericType: null,
    isFormValid: null,
    placeholder: null,
    onChange: null,
    disabled: null,
    children: null,
    vMin: null,
    vMax: null,
    prefix: null,
    suffix: null
};


FormAutonumeric.propTypes = {
    validationRules: PropTypes.shape({
        [PropTypes.string]: PropTypes.oneOfType([
            PropTypes.string,
            PropTypes.number,
            PropTypes.bool
        ])
    }),
    onBlur: PropTypes.func,
    onFocus: PropTypes.func,
    inputClasses: PropTypes.string,
    showErrors: PropTypes.bool,
    numericType: PropTypes.string,
    value: PropTypes.oneOfType([PropTypes.string, PropTypes.number]).isRequired,
    isFormValid: PropTypes.func,
    id: PropTypes.string.isRequired,
    placeholder: PropTypes.string,
    onKeyUp: PropTypes.func.isRequired,
    onChange: PropTypes.func,
    disabled: PropTypes.bool,
    children: PropTypes.element,
    vMin: PropTypes.string,
    vMax: PropTypes.string,
    prefix: PropTypes.string,
    suffix: PropTypes.string
};
like image 785
HasanG Avatar asked Oct 25 '25 04:10

HasanG


1 Answers

I agree with Raul Rene's comment. Any unused props will be undefined which propbably won't make any difference in your code unless you are making strict checks, such as myProp !== null or something.

If you want to keep using defaultProps but still shorten your code a bit, you could always add the isRequired property to those props which are absolutely necessary for your component to work. For example, your component probably won't work as expected if the onBlur and onFocus props are not passed in, whereas it probably will work fine if children or disabled are not explicitly passed in.

Here's what this change would look like:

onBlur: PropTypes.func.isRequired,
onFocus: PropTypes.func.isRequired,

and remove these props from your defaultProps definition. A "fallback" prop doesn't make sense if a prop is "required" to be explicitly passed to the component.

I don't know how your code looks for your component, but the prop names suggest that your defaultProps definition can be reduced by at least half with this change.

like image 164
Chris Avatar answered Oct 26 '25 18:10

Chris



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!