Day 7 of #100daysofcode
Today we will learn how to validate custom React component props with proptype. Our initial code will be :
When you create a React component, others may want to use it and may not utilize it correctly. As you can see, we have a react function component that takes
lastname as input and returns the result. As you've seen, we gave false as an input to our
firstname and nothing to our
lastname in the
const element, but we want both
lastname as strings. We will utilize a feature proptype to evaluate how props given to the component are used.
Here we have a function that checks whether or not our
propName is a string. If not, an
error message is displayed. If you want the same thing for
lastname, we must repeat what we did for
firstname. Instead, we can create a variable like :
You can also use this to determine whether your prop is a string, boolean, array, or something else. More information can be found here.
Our finished code should look something like this :