![]() ![]() This is because PropTypes is great for development, but it does slow things down a bit in an unnecessary way for production. You'll notice now that our PropTypes validation is totally gone. ![]() Let's swap the development version of react to the production version. ![]() For components declared as classes like this, we can continue to specify our PropTypes the same way, but it's more common to do this by making PropTypes a static property of the class like this. That will give us a new error indicating that this prop is required. is required here for the first name and here for the last name. If we want it to specify a prop as required, we can simply. That's useful in some cases like where we provide a default value, like if were to add or unknown here for the last name. The issue here is that all of the validators in the PropTypes module consider props to be optional by default, so if a prop is not provided, then the validator doesn't run. We're no longer getting the warning for the last name prop. We can go ahead and remove our own implementation of PropTypes, and everything should work pretty much the same. That's going to add a PropTypes global to our program. I'll go ahead and add a new script tag up here at the top that pulls in PropTypes from unpackage. Because this and other PropTypes are so common, the react team has built a package called PropTypes which we can use just like the one we just built ourselves. Now, we're getting the error message for both of them. Then, we can set first name to proptypes.string, and last name and set that to proptypes.string as well. We need the same thing for the last name, so we'll pull this function out to an object that we'll call PropTypes and put it in a property called string. Let's go ahead and say, if type of props at prop name is not equal to string, then we'll return a new error, "Hey, you should pass a string for prop name in component name, but you passed a type of props at prop name." With that, we'll see our error message being logged to the console here. The value of this is a function which accepts props, prop name, and component name. To validate the first name prop, we'll add a first name key to this object. To use PropTypes on a function component like say hello here, we'll say sayhello.proptypes is an object. What is being rendered is not what we'd expect. We're not passing a last name prop at all. For example, here we're passing the value of true for first name which we're expecting to be a string in our component. Instructor: When other people start using your components, sometimes they'll make mistakes when passing props. ![]()
0 Comments
Leave a Reply. |
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |