Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ReactJS "TypeError: Cannot read property 'array' of undefined"

While running this code I got error on the first line on App.propTypes

TypeError: Cannot read property 'array' of undefined

Code:

  class App extends React.Component {
   render() {
      return (
         <div>
            <h3>Array: {this.props.propArray}</h3>
            <h3>Array: {this.props.propBool ? "true" : "false"}</h3>
            <h3>Func: {this.props.propFunc(3)}</h3>
            <h3>Number: {this.props.propNumber}</h3>
            <h3>String: {this.props.propString}</h3>
            <h3>Object: {this.props.propObject.objectName1}</h3>
            <h3>Object: {this.props.propObject.objectName2}</h3>
            <h3>Object: {this.props.propObject.objectName3}</h3>
         </div>
      );
   }
}


App.propTypes = {
   propArray: React.PropTypes.array.isRequired, //I got error over here
   propBool: React.PropTypes.bool.isRequired,
   propFunc: React.PropTypes.func,
   propNumber: React.PropTypes.number,
   propString: React.PropTypes.string,
   propObject: React.PropTypes.object
}

App.defaultProps = {
   propArray: [1,2,3,4,5],
   propBool: true,
   propFunc: function(e){return e},
   propNumber: 1,
   propString: "String value...",

   propObject: {
      objectName1:"objectValue1",
      objectName2: "objectValue2",
      objectName3: "objectValue3"
   }
}

I tried to search but I didn't get the correct solution.

like image 456
Harsh Patel Avatar asked Oct 13 '17 04:10

Harsh Patel


1 Answers

Prop-Types are now a separately maintained library named prop-types Here is the explanation from react-docs: https://reactjs.org/docs/typechecking-with-proptypes.html

You have to import them as

import React from 'react';
import PropTypes from 'prop-types'

class App extends React.Component {
  //App here
}

App.propTypes = {
 propArray: PropTypes.array.isRequired, 
 propBool: PropTypes.bool.isRequired,
 propFunc: PropTypes.func,
 propNumber: PropTypes.number,
 propString: PropTypes.string,
 propObject: PropTypes.object
}

NPM Package

like image 173
Agney Avatar answered Sep 25 '22 23:09

Agney