Without special invitation I was on React documentation here aiming to play with the idea of defaultProps. I got TypeError that I can not understand!
import React, {PropTypes} from 'react';
import ReactDOM from 'react-dom';
class Greeting extends React.Component {
render() {
return (
<h1>Hello, {this.props.name}</h1>
);
}
}
Greeting.defaultProps = {
name: 'Stranger'
};
Greeting.propTypes = {
name: PropTypes.string,
};
ReactDOM.render(<Greeting/>, document.getElementById('root'));
Result:
Uncaught TypeError: Cannot read property 'string' of undefined
Pointing to (in Sources):
name: _react.PropTypes.string
As you read in documentation:
The propTypes typechecking happens after defaultProps are resolved, so typechecking will also apply to the defaultProps.
If I remove:
Greeting.propTypes = {
name: PropTypes.string, //.isRequired
};
There will be no TypeError!
Please, how I could understand this and have both propTypes and defaultProps without getting TypeError if I didn't explicitly provide a prop that has a default value assigned (which is why default value exists)?