HiveBrain v1.2.0
Get Started
← Back to all entries
snippetreactCritical

How do you validate the PropTypes of a nested object in ReactJS?

Submitted by: @import:stackoverflow-api··
0
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:

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 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.