”;
One of the time consuming process in a program is to find the root cause of a bug. In react, props are used extensively. Props of a component will have different source of origin. Some component will have static props, while some component will have dynamic props coming from immediate parent component. One of the source of bugs is that the value of the props does not match the type of the props designed by the developer. This mismatch create a lot of bugs. React provides a lot of option to fix this and one such feature is PropTypes and its validation.
We will learn what is PropTypes and how to use it to create a bug free react application in this chapter.
PropTypes
React community provides a special package, prop-types to address the properties type mismatch problem. prop-types allows the properties of the component to be specified with type through a custom setting (propTypes) inside the component. For example, properties with number type can specified using PropTypes.number option as shown below.
Sum.propTypes = { num1: PropTypes.number, num2: PropTypes.number }
Once the type of the properties is specified, then the React will throw warning during the development phase of the application.
Let us include propTypes in our application and see how it helps to catch properties type mismatch issue.
First of all, create a new react application and start it using below command.
create-react-app myapp cd myapp npm start
Next, install prop-types package using node package manager (npm) as shown below −
npm i prop-types --save
Next, open App.css (src/App.css) and remove all the CSS classes. Then, create a simple component, Sum (src/Components/Sum.js) as shown below −
import React from ''react'' import PropTypes from ''prop-types'' class Sum extends React.Component { render() { return <p>The sum of {this.props.num1} and {this.props.num2} is {parseInt(this.props.num1) + parseInt(this.props.num2)}</p> } } Sum.propTypes = { num1: PropTypes.number, num2: PropTypes.number } export default Sum
Here,
-
Purpose of the component is to find sum value of the given props (num1 and num2) and show it in the front end.
-
Set the data type of the num1 and num2 as numbers (PropTypes.number) using propTypes.
Next, open App component (src/App.js), import the bootstrap css and render the date picker as shown below −
import ''./App.css'' import Sum from ''./Components/Sum'' function App() { return ( <div className="container"> <div style={{ padding: "10px" }}> <div> <Sum num1="10" num2="John" /> </div> </div> </div> ); } export default App;
Here, we have rendered the Sum component with 10 and John as props
Finally, open the application in your favorite browser and open the JavaScript console through developer tools. JavaScript throws the warning that the unexpected type is provided as shown below.
propTypes only works during development phase to nullify the performance reduction of the application due to additional checking of the props types. This will not affect the performance of the application in production / live setup.
Available validators
The prop-types supplies a good collection of ready-made validators. They are as follows −
-
PropTypes.array
-
PropTypes.bigint
-
PropTypes.bool
-
PropTypes.func
-
PropTypes.number
-
PropTypes.object
-
PropTypes.string
-
PropTypes.symbol
-
PropTypes.node – Anything that can be rendered
-
PropTypes.element – React component
-
PropTypes.elementType – Type of React component
-
PropTypes.instanceOf() – instance of the specified class
-
propTypes.oneOf([”Value1”, ”valueN”]) – one of Value and ValueN
-
PropTypes.oneOfType([]) – Example, PropTypes.oneOfType([PropTypes.number, PropTypes.bigint])
-
PropTypes.arrayOf() – Example, PropTypes.arrayOf(PropTypes.number)
-
PropTypes.objectOf() – Example, PropTypes.objectOf(PropTypes.number)
-
PropTypes.func.isRequired
-
propTypes.element.isRequired
-
PropTypes.any.isRequired
Custom validator
A custom validator can also be created and used to validate the property”s value. Let us consider that the component have a email property and the value should be a valid email address. Then, a validate function can be written and attached to the email property as shown below −
Sum.propTypes = { num1: PropTypes.number, num2: PropTypes.number, email: function(myProps, myPropName, myComponentName) { if (!/^[^s@]+@[^s@]+.[^s@]+$/.test(myProps[myPropName])) { return new Error( ''Invalid prop value `'' + myProps[myPropName] + ''` supplied to'' + '' `'' + myComponentName + ''/'' + myPropName + ''`. Validation failed.'' ); } } }
Here,
-
/^[^s@]+@[^s@]+.[^s@]+$/ is a simple regex email pattern.
-
myProps represents all properties.
-
myPropName represent the current property being validated.
-
myComponentName represent the name of the component being validated.
Similarly, custom validator can be created and used for array and object properties using below function signature −
PropTypes.arrayOf(function(propValue, key, componentName, location, propFullName) { ... })
Here,
-
propValue represents array / object value.
-
key represents the key of the current item.
-
componentName represents the name of the component.
-
propFullName represents the name of the property being validated.
Summary
Props types is one of the good tool for the developer to write bug free software. It will definitely help the developer to code faster and safer.
”;