What should be react default prop type for PropTypes.shape?

1.1k views Asked by At

Say I have the following condition:

    static propTypes = {
        deployment: PropTypes.shape({
            getMetrics: PropTypes.func.isRequired,
            getRootMetric: PropTypes.func.isRequired
       }).isRequired,
}

How would I declare the default for deployment ? Would it be undefined or would it be [] ?

3

There are 3 answers

0
Code-Apprentice On BEST ANSWER

Since the prop is required, I see no reason to define a default. Defaults are only useful for optional props which also have a reasonable default value, such as an empty list [] or an empty object {}.

0
Daniel Andrei On

You could not define a default prop or you could just say {getMetrics: () => {}, getRootMetric: () => {}} since it's an object. However, required props don't really need defaults, otherwise they wouldn't really be required.

To give an example : You build a small npm module that comes along with a config object

  • You can define this object as required (the module would break
    without users providing it)
  • You can provide defaults (it would work with these if not provided)

So, finally, it's up to you if and how you provide defaults.

0
Anthony N On

I would use something like the below:

SomeComponent.defaultProps = {
  deployment: {
    getMetrics: () => {},
    getRootMetric: () => {}
  }
}

Defaults are good when not having the values would break your app.