Reputation: 591
React provides proptypes for type checking as the following code block demonstrates:
import PropTypes from 'prop-types';
class Greeting extends React.Component {
render() {
return (
<h1>Hello, {this.props.name}</h1>
);
}
}
Greeting.propTypes = {
name: PropTypes.string
};
But I can do the following as well for the 'name' proptype:
Greeting.propTypes = {
name: String
};
In the later case i don't need to include the 'prop-types' module. Which one is the recommended approach?
Upvotes: 0
Views: 548
Reputation: 5243
The first way is the recommended way.
When you do
Greeting.propTypes = {
name: String
};
you are defining a javascript string field inside your proptypes object. Also, you will not be able to make the prop a required prop by using the above.
By using this
Greeting.propTypes = {
name: Proptypes.string.isRequired
};
you can make the proptype required and show a console warning if it is not supplied.
Upvotes: 1