snippetreactCritical
How do you validate the PropTypes of a nested object in ReactJS?
Viewed 0 times
validateyoutheobjectreactjsnestedhowproptypes
Problem
I'm using a data object as my props for a component in ReactJS.
I know its easy to validate the PropTypes object itself:
But what if I want to validate the values inside? ie. data.id, data.title?
I know its easy to validate the PropTypes object itself:
propTypes: {
data: React.PropTypes.object
}But what if I want to validate the values inside? ie. data.id, data.title?
props[propName]: React.PropTypes.number.required // etc...Solution
You can use
Update
As @Chris pointed out in comments, as of React version 15.5.0
More info
React.PropTypes.shape to validate properties:propTypes: {
data: React.PropTypes.shape({
id: React.PropTypes.number.isRequired,
title: React.PropTypes.string
})
}Update
As @Chris pointed out in comments, as of React version 15.5.0
React.PropTypes has moved to package prop-types.import PropTypes from 'prop-types';
propTypes: {
data: PropTypes.shape({
id: PropTypes.number.isRequired,
title: PropTypes.string
})
}More info
Code Snippets
propTypes: {
data: React.PropTypes.shape({
id: React.PropTypes.number.isRequired,
title: React.PropTypes.string
})
}import PropTypes from 'prop-types';
propTypes: {
data: PropTypes.shape({
id: PropTypes.number.isRequired,
title: PropTypes.string
})
}Context
Stack Overflow Q#26923042, score: 412
Revisions (0)
No revisions yet.