0

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)?

0

1 Answer 1

2

The error tells you that PropTypes is undefined, meaning there is an issue with what you're importing. You should import PropTypes from prop-types:

import PropTypes from 'prop-types';

https://reactjs.org/docs/typechecking-with-proptypes.html

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks. I imported it, but as "import React, {PropTypes} from 'react';"
and the funny is that I was practicing by a video tutorial that was not updated, only your answer recalled me that it's updated and no more where I imported from!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.