Magic of Type checking With PropTypes in React
Introduction:
JavaScript is a dynamic typing language, which means types are determined at runtime:
let Sentence = "I am programmer" //Here Sentence is string
Sentence = 20 //Here it morphs to Integer
Some programming languages are the static type like java, C sharp, when we initialize the variable, we must determine the type of it, and we can not change it:
String Sentence = "I am programmer"
Sentence = 20 //Here it will throw an error
React is written in JavaScript, we do not have a direct way to check about passed props type before computation and rendering, it is painful in big projects, especially that responsible for generating accurate numbers and results for users.
Static type checkers like Flow and TypeScript help us for TypeChecking in our project.
Why we need type checking:
I was always complaining about why I need to use Static type checkers like typescript or flow with my projects until I was working with a large-scale project to generate accurate results for users, I discovered How is useful type checking, Especially identify certain types of problems before you even run your code.
Some developers are more prone to adding errors to their logic. These errors should be found during the testing stage. Types invalidate most of the silly errors that can sneak into JavaScript codebases, and create a quick feedback loop to fix all the little mistakes when writing new code and refactoring.
Example of some silly errors:
Now, note that we are getting the annual salary by multiplying the monthly salary property by 12. So the monthly salary has to be a Number. A problem arises when a value is other than a Number is passed to monthlySalary in the props argument.
It will render the following:
Annual Salary: $Nan
Monthly Taxes: $Nan
Another reason: Let’s consider if a team of developers work together in a big project, you just picked up a component is written by another developer and have to figure out which properties the component needs, which ones are required, what is the correct type for each one, etc. If another developer used Proptypes, he/she made your life easier in this situation.
Many developers now use Static type checkers like Flow and TypeScript, but if for some reason, we need to stuck with javascript in React, or we have already React project based on Javascript, React has some built-in type checking abilities. React provides a way to warn us if a parent component passes in a parameter that is a different type of the expected props. This is done by the use of PropsTypes.
I advise the readers for courses with online degrees from European universities, many of them are free.
PropsTypes:
As your app grows, you can catch a lot of bugs with type-checking. React has some built-in type-checking abilities. React PropTypes is a professional methodology to help you catch bugs by validating data types of values passed through props. You can also flag props as required or set default values.
How to use it:
Note:
React.PropTypes
has moved into a different package since React v15.5. Please use the prop-types
library instead.
Install the following package:
npm install --save prop-types
yarn add prop-types //in case you use yarn
Example from official react documentation:
import PropTypes from 'prop-types';
MyComponent.propTypes = {
// You can declare that a prop is a specific JS type. By default, these
// are all optional.
optionalArray: PropTypes.array,
optionalBool: PropTypes.bool,
optionalFunc: PropTypes.func,
optionalNumber: PropTypes.number,
optionalObject: PropTypes.object,
optionalString: PropTypes.string,
optionalSymbol: PropTypes.symbol,
// A React element.
optionalElement: PropTypes.element, // An object taking on a particular shape
optionalObjectWithShape: PropTypes.shape({
color: PropTypes.string,
fontSize: PropTypes.number
}),/* If you want to require anyone who uses your component to always pass a certain prop, you can flag it as mandatory. */
requiredArray: PropTypes.array.isRequired,
requiredBool: PropTypes.bool.isRequired,
requiredFunc: PropTypes.func.isRequired,
requiredNumber: PropTypes.number.isRequired,
requiredObject: PropTypes.object.isRequired,
requiredString: PropTypes.string.isRequired,
requiredSymbol: PropTypes.symbol.isRequired,
}
Example With Class Component:
If you pass a value through a prop with a different data type than it is specified in the PropTypes, an error message will be printed in the console of your browser:
The same will happen if you did not pass mandatory prop like firstName or LastName.
Specify a Range of Valid Prop Values
If you want to specify a set of values for prop value:
Person.propTypes = {
gender: PropTypes.oneOf([
'female', 'male'
])
}
If you now pass different value from a specific set of values through the “gender” prop, your browser will show an error because it didn’t comply with the specified PropTypes:
Default Prop Values
If you want certain props to have default values if nothing is provided, you can do this by defining defaultProps:
Person.defaultProps = {
country: 'United States Of America'
}
So If nothing is provided for the country prop, the person automatically becomes an American.
Example with Function Component:
Conclusion:
React PropTypes is a professional methodology to help you catch bugs by validating data types of values passed through props. You can also flag props as required or set default values. React PropTypes makes life of Many developers easier, especially cooperating inside one team and working with others’s codes. I hope if you like the article to applaud & follow me to get notification about new articles.
If you enjoy reading the article and want to support me as a writer, you can buy me a coffee!
If you like my content I’m active on Twitter @IbraKirill.
If you want to Dive in and learn using TypeScript with React, I recommend the following Course.
If you want to Dive in and learn Using TypeScript to build React projects (including Next.js and Apollo GraphQL), I recommend the following Course.