Hi All,
I have the code below to check for prop type where I set the prop type of nameit to be number but when I set the default prop of nameit to be a string I am not getting a warning in the browser web dev console window indicating the prop type is wrong.
What am I doing wrong?
My code is:
class Contacts extends React.Component {
constructor(props) {
super(props);
}
render() {
return (
<div>{this.props.nameit}</div>
);
}
}
Contacts.propTypes = {nameit: PropTypes.number}
Contacts.defaultProps = {nameit: 'Dog'}
ReactDOM.render(<Contacts/>, document.getElementById('container'))
AFAIK Proptypes are checked on assignment, and if you populate the default with a wrong type, React will assume you know what you’re doing. Try creating the component with a bad type, like:
<Contacts nameit={{'Dog'}} />
I removed the Contacts.defaultProps = {nameit: 'Dog'} and updated the render line as
ReactDOM.render(<Contacts nameit={{'Dog'}}/>, document.getElementById('container'))
but still no prop type warning. Now Dog is not even rendered at all.
Are you by any chance running a prod build instead of dev? If you have the dev tools installed, that will tell you.
I do Vue for a living, so I’m just going by memory when it comes to React.
It looks like it is a prod version (see link below). I am using codepen by the way. What link should I use?
https://cdnjs.cloudflare.com/ajax/libs/react/16.13.1/umd/react.production.min.js
Just substitute ‘production’ with ‘development’. I usually build react/vue/whatever into my apps with webpack, and that takes care of picking the right version at build time.
Here’s React’s entry on the cloudflare cdn:
Thanks. Still didn’t work but I was able to put my code in react app and get the warning so I assume the problem is related to codepen.
Anyway thanks for the help.
Yah, create-react-app is a much better sandbox than codepen for anything react-related, and it will do that automatic dev/prod build too. The other big frameworks have similar tools.
Codepen and such are great for self-contained demos you want to put out there, but for actual dev work, nothing beats npm and webpack (CRA is basically a fancy preset for those)
1 Like