Zhao Yi Zhao Yi - 1 year ago 106
React JSX Question

PropTypes in react es6 doesn't work

I created a component and want to validate one of its property. But it seems the validation doesn't work. When I access this component, I always got below property undefined error:

Cannot read property 'map' of undefined

Below is my component definition.

import React, {Component, PropTypes} from 'react'
import Carousel from 'nuka-carousel'

export default class DiagnosticSchedule extends Component {

render() {
let {style, diagnostics, afterSlide, beforeSlide} = this.props
// if(diagnostics === undefined){
// return (<div/>)
// }
return (
<div style={style}>
<Carousel style={style} decorators={null} afterSlide={afterSlide} beforeSlide={beforeSlide}>
diagnostics.map(diagnostic => {
return (
<div style={styles.message}>



DiagnosticSchedule.propTypes = {
diagnostics: PropTypes.array.isRequired,

const styles = {

message: {
fontSize: 'xx-large',
flex: 1,
backgroundColor: 'red',
alignSelf: 'center',
lineHeight: '5',
zIndex: 100,
width: '100%',
textAlign: 'center',

I think below code is used to validate this component's property.

DiagnosticSchedule.propTypes = {
diagnostics: PropTypes.array.isRequired,

but it still complains that the diagnostics is an undefined object.

Do I miss anything or do I misunderstand the PropTypes validation? What is the expected behavior of PropTypes?


Answer Source

The error happens because the diagnostics prop doesn't get a default value. If you don't pass the prop, it will be set to undefined. To fix the situation, you can set defaultProps like this:

DiagnosticSchedule.defaultProps = {
    diagnostics: []
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download