Add Validate to Components’ Props

Tram Ho

Hello friends. Lately, my family’s home has been flocking to React. I’m also curious why react is so hot, so I started testing and started testing it. Learn for a while, the GL brothers organized training and made a project to demo. There is nothing worth saying if I do not encounter some banana bugs. The error was messy again so I don’t know where that time @@ There were bugs I found out nearly in the morning. This is annoying, just because the props are in the wrong type At that time, thanks to my brother sitting right behind to ask for guidance, I knew the react had a package of prop-types to validate the pile of props and slapped my face with an error to correct the props. That said, I really like this package, so I don’t have to eat onions because of the silly bugs due to the wrong props. If you switch from C #, C or Java to Js, it is really annoying with variable declaration without data type. Because of that, when I used that variable elsewhere, I no longer realized what type it was. In React, it is even more forgotten when passed through props of dozens of components. Let’s find out together.

How to add typechecking to components

It’s really easy, guys, assuming you have data like this (picture below)

Statistics, now there are 2 files like this ListPets.js and Pet.js

The simple scenario is that ListPet will pass props through the Pet to display the corresponding data.

Now if I edit line 29 of the ListPets file to

In Europe, we will encounter one of these bugs:

ListPets: I have passed all the props, show it Pet: I need an object, but what is it I don’t understand

Then always. When I see this error I will think: oh I am right. Yes the right beep. Underfind a mountain: v But it’s worth mentioning that turning on the console made a mistake, huhu now. Only when I report an error, can I correct it? Now we need 1 error message is everything immediately. If the flu has a tiffy, the validate props have prop-types

With the above setup, when calling the Pet component, it will immediately give us an error message when passing the wrong props as follows:

Okay, and so we can realize the carelessness of passing the wrong props. Now that we correct the props that the Pet component wants, we will have our beloved Pets list appear

summary

  1. Javascript is a language that doesn’t provide data type
  2. Prop-types are a simple way to minimize data transmission errors.
  3. With Prop-types, we will know immediately which subcomponents need the data type to display properly.
  4. Do not forget to import the library before using: v

You can read more at the docs https://reactjs.org/docs/typechecking-with-proptypes.html

# Reference https://medium.com/dailyjs/how-to-add-typechecking-to-your-react-components-223c5560ba58

Share the news now

Source : Viblo