Can a default value be used in a proptype shape?
Asked Answered
C

2

6

Is it possible to define a type for an object's with a required key value pair and a default key value pair?

Example:

const myComponent = (props) => {
  const {
    myObject: {
      someRequiredString,
      someNotRequiredString,
    }
  }
}

myComponent.propTypes = {
  myObject: PropTypes.shape({
    someRequiredString.string.isRequired,
  }).isRequired,
}

myComponent.defaultProps = {
  myObject: {
    someNotRequiredString: '',
  }
}
Consummation answered 13/8, 2019 at 11:32 Comment(2)
Usually required field didn't have a default valueSuctorial
True, but how about an object which has both a required and not required field? @VadimHulevichConsummation
S
4

So if i understand you correct, you need non-required object bit if this object exist it's must have 2 required field, and maybe one non-required

So here we are:

componentForUser.propTypes = {
    myObject: PropTypes.shape({
        name:PropTypes.string.isRequired,
        secondName:PropTypes.string.isRequired,
        age:PropTypes.string,
    }),
}

componentForUser.defaultProps = {
    myObject: {
        name: 'defaultName',
        secondName: 'defaultSecondName',
        age:21
    }
}

In this case if User object is not required, instead of this you will get User with properties:

myObject: { name: 'defaultName', secondName: 'defaultSecondName', age:21 }

But if from props you will get object User without name, you catch Warning about required name and secondName.

Suctorial answered 13/8, 2019 at 13:6 Comment(1)
So the trick is to not set .isRequired on the object in the propTypes. Perfect!Consummation
R
1

Maybe this has changed since this question was asked, but you can't provide defaultProps for a nested value like this.

Remonstrate answered 28/4, 2021 at 15:13 Comment(1)
No, as per this answer, but there is a workaround explained.Chemist

© 2022 - 2024 — McMap. All rights reserved.