Day 7 of #100daysofcode

Harshad Rathod
2 min readJun 25, 2022

--

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 firstname and 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 firstname and 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 :

This is so popular that the react team created a package on npm that you can use with this :

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 :

That’s all there is to toady.

--

--

Harshad Rathod

I write about anime, programming,books, etc. or whatever I like about.