id/name are required for the/any user.
For the component in question I require there is a user at all.
So wonder is the above definition correct, or should I also add .isRequired to the whole object? Making it:
Not sure if I understand your question correctly, but you would use PropTypes on a component, not an object.
So, if you have a User component, you would use PropTypes to enforce that the User component gets passed a prop named id and a prop named name, like this:
On the other hand, if you have a UserList component, that has a user prop that is an object, you would set id and name properties of the user object as isRequired and that would give you a warning if the user is not passed in at all.
UserList.propTypes = {
user: PropTypes.shape({
id: PropTypes.number.isRequired // required property user
name: PropTypes.string.isRequired // required property of user
})
}
Hey, no sorry what I meant was the user was an object, I should have denoted it with the shape type.
Although I wasn't sure if the user would automatically be required if all of its props were required, like this:
user: PropTypes.shape({
id: PropTypes.string.isRequired // required property user
name: PropTypes.string.isRequired // required property of user
})
I figured out that in the above, those props are only required if the user is passed in at all. To also ensure a user is passed, not just a valid user I needed:
Hi, nice article thanks.
I have one question: How should objects be marked as required.
Let's say I have an object:
id/name are required for the/any user.
For the component in question I require there is a user at all.
So wonder is the above definition correct, or should I also add
.isRequired
to the whole object? Making it:So tl;dr; are objects that have required properties, automatically required themselves? Or are the properties only required If an object is passed in?
Not sure if I understand your question correctly, but you would use PropTypes on a component, not an object.
So, if you have a
User
component, you would use PropTypes to enforce that theUser
component gets passed a prop namedid
and a prop namedname
, like this:On the other hand, if you have a
UserList
component, that has auser
prop that is an object, you would setid
andname
properties of theuser
object asisRequired
and that would give you a warning if the user is not passed in at all.Hope this makes sense.
Hey, no sorry what I meant was the user was an object, I should have denoted it with the shape type.
Although I wasn't sure if the user would automatically be required if all of its props were required, like this:
I figured out that in the above, those props are only required if the user is passed in at all. To also ensure a user is passed, not just a valid user I needed:
Shall leave it here in case it helps anyone else.
Thanks Sam, my eslint was throwing error and this fixed it!