it must be a function, usually from React.PropTypes

Viewed 47331

I want to pass string from Main to Header. It succeeds but warning. I'm a beginner of React so I can not figure out what it must be a function means.

Anyone knows how to solve this warning?

The warning is:

enter image description here

And my code is below:

Main.js

import React from 'react';

import Header from './Header';
import AppList from './AppList/AppList';
import Footer from './Footer';

const propTypes = {
  mainInfo: React.PropTypes.shape({
    title: React.PropTypes.string.isRequired,
    apps: React.PropTypes.array.isRequired,
  }),
};

class Main extends React.Component {
  static methodsAreOk() {
    return true;
  }

  render() {
    return (
      <div>
        <Header title={this.props.mainInfo.title} />
        <AppList apps={this.props.mainInfo.apps} />
        <Footer />
      </div>
    );
  }
}

Main.propTypes = propTypes;

export default Main;

Header.js

import React from 'react';

const propTypes = {
  title: React.PropTypes.string.isRequred,
};

class Header extends React.Component {
  static methodsAreOk() {
    return true;
  }

  render() {
    return (
      <div className="header">
        <h1>{this.props.title}</h1>
      </div>
    );
  }
}

Header.propTypes = propTypes;

export default Header;
8 Answers

In my case it happened when I declared Component.propTypes and below that, instead of writing Component.defaultProps I wrote again Component.propTypes assigning the default values.

Something similar to isRequred instead of isRequired happened to me. I was trying to define the default props, but copy-pasted the propTypes and never changed the name, so I ended up with something like this:

import PropTypes from 'prop-types'

const Main = ({ title }) => // whatever

Main.propTypes = {
  title: PropTypes.string
}

Main.propTypes = { // this should have been Main.defaultProps! ‍♂️
  title: 'This is the default title!'
}

So PropTypes was complaining about the title's prop type not being the right thing. It said something like "it must be a function, usually from React.PropTypes but it was a string".

I thought I was going crazy. I was looking at the first Main.propTypes and trying to find typo or anything that could be wrong, but as you can see it was completely fine. I opened multiple files that had prop types defined but weren't throwing the error.

I was obviously looking at the wrong place but eventually found it out of luck. I was pretty lucky to actually find it. These facepalming bugs are quite hard to figure out because they're like a magician moving one hand to attract all the eyes while preparing the trick with the other one, usually in plain sight.

Related