React: PropTypes in a stateless functional component

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

List:

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;

Apprendering 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 pass this.state.todosin List. Since this this.state.todosis a string, I was expecting Prop type confirmation. Instead, I get an error in the browser console because the lines do not have a method called map.

Why does Prop type checking not work properly? Takin take a look at this question , the case seems identical.

+4
source share
1 answer

You have to change

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

to

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

Source: https://habr.com/ru/post/1682602/


All Articles