84

In React, I wrote a stateless functional component and now want to add Prop Type validation to it.

List component:

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

function List(props) {
  const todos = props.todos.map((todo, index) => (<li key={index}>{todo}</li>));
  return (<ul></ul>);
}

List.PropTypes = {
  todos: PropTypes.array.isRequired,
};

export default List;

App component, rendering List:

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

class App extends React.Component {
  constructor() {
    super();
    this.state = {
      todos: '',
    };
  }

  render() {
    return (<List todos={this.state.todos} />);
  }
}

export default App;

As you can see in App, I am passing this.state.todos to List. Since this.state.todos is a string, I expected Prop Type validation to kick in. Instead, I get an error in the browser console because strings don't have a method called map.

Why is the Prop Type validation not working as expected? Takin a look at this question, the case seems identical.

Darren Shewry
  • 10,179
  • 4
  • 50
  • 46
Sven
  • 12,997
  • 27
  • 90
  • 148

1 Answers1

142

You should change the casing on the property to propTypes:

- List.PropTypes = {
+ List.propTypes = {
    todos: PropTypes.array.isRequired,
  };

Correct:

List.propTypes = {
  todos: PropTypes.array.isRequired,
};

(The instance of a PropTypes object is lowercase, but the Class/Type is uppercase. The instance is List.propTypes. The Class/Type is PropTypes.)

KyleMit
  • 30,350
  • 66
  • 462
  • 664
Bhargav Ponnapalli
  • 9,224
  • 7
  • 36
  • 45
  • Quick and easy, thank you! I simply overlooked that, d'oh. – Sven Jul 30 '17 at 10:28
  • 4
    To illuminate this kind of dirty errors you can use https://github.com/yannickcr/eslint-plugin-react/blob/master/docs/rules/no-typos.md – Sergey Orlov Sep 10 '17 at 16:48
  • 1
    For clarity, if anyone cares about the distinction, `List.propTypes` is *not* in fact an instance of `PropTypes`. It's a plain javascript object. In fact, `PropTypes` isn't even a class: it's also an object. Instance in this answer is not meant in the object-oriented sense. – Stone Mason May 31 '19 at 03:25
  • 1
    Classes are objects – challet Dec 24 '19 at 12:06