Adding Type Validation To Props in React

If you're using React to create an interface, chances are you want to control the type of data flowing through your app. For example, it's important to make sure that form data is getting sent to the back-end is ready to be perfectly parsed and saved into the database.  One way to both take the initiative on this front and help developers you collaborate with is to use propTypes, React's built-in prop validation tool. 

Getting started is simple, just add a new statement at the end of each component that uses props. If you've got an existing application, you can even just search through the file for each unique use of props.  

For example, if your component named MyComponent takes a prop named tagline that should always be a string, then your propTypes declaration will look like this. 

MyComponent.propTypes = {
  tagline: React.PropTypes.string

Should someone else accidentally send a different data type through, the validator will fail and you'll get a helpful bug in the developer's console. 

Screenshot 2017-12-17 18.42.39.png

Proptypes have a wide variety of available methods. For example, if you want to validate a form with a string userName, integer userId, order object, and function removeFromOrder, you can do so with the following declaration. 

myComponent.propTypes = {
    order: React.PropTypes.object.isRequired,
    userId: React.PropTypes.number.isRequired,
    userName: React.PropTypes.string.isRequired,
    removeFromOrder: React.PropTypes.func.isRequired

Notice how all of the propTypes declared in this example are appended with the isRequired function. If any of them aren't sent through, we can also expect an error available in the console. 

Ultimately, propTypes are a valuable addition to any React app. They can help both fellow developers and users ensure that valid information is sent to back-end services and APIs, preventing errors and streamlining the development workflow. For more information and the full possibility of functions, read the docs!