Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React propType cannot read property of undefined

Tags:

reactjs

Using propTypes to validate props gives the following error:

TypeError: Cannot read property 'string' of undefined.

TypeError: Cannot read property 'func' of undefined.

The code in question is at the bottom of the snippet:

import React from 'react';
import ProjectItem from './ProjectItem';

class Projects extends React.Component {
    
    deleteProject(title) {
      this.props.onDelete(title);
    }

    render() { 
      let projectItems;

      if (this.props.project) {
        projectItems = this.props.project.map(project => {
            return (
                <ProjectItem key={project.title} project={project} onDelete={this.deleteProject.bind(this)}  />
            )
        });
      }
    
      return (
        <div className="Projects">
          {projectItems}
        </div>    
      );    
    }

}

Projects.propTypes = {
  projects: React.PropTypes.string,
  onDelete: React.PropTypes.func
}
like image 997
Nizar Ali Hunzai Avatar asked Oct 14 '17 19:10

Nizar Ali Hunzai


2 Answers

You need to install the prop-types package and then add the import statement

import PropTypes from prop-types;

at the top of your class.

The PropTypes have been moved from React to their own package prop-types.

EDIT: As mentioned in the comments, this is only applicable for React version 15.5 and above.

like image 61
palsrealm Avatar answered Oct 13 '22 10:10

palsrealm


As palsrealm mentioned, you need to add the prop-types package, and then remove React before Proptypes. The following should work:

Projects.propTypes = {
   projects: PropTypes.string,
   onDelete: PropTypes.func
}
like image 35
Cameron Avatar answered Oct 13 '22 11:10

Cameron