Updated April 11, 2023
Introduction to React PropTypes
React has an in built mechanism to add type checking for the components. A special property called PropTypes is used for setting up the type checking. The props are checked against the configured type definitions whenever the props pass to a React Component. A warning pops up on the JavaScript console whenever an invalid value is passed. The values need to be resolved if a default prop is passed to a React Component, before checking the type against the PropType. This also concludes that default values also have to be checked against the PropTypes definitions.
Different PropTypes and their Working
Different validators are exported by the PropTypes to configure type definitions.
Validators used for basic data types are stated below:
- any: Props of any data type can get validated by this.
- symbol: Props with symbol data type can be validated by this.
- func: Function PropType can be used for validation by this validator.
- array: Prop with an array data type can get validated by this.
- bool: Props with Boolean data type can get validated by this.
- string: Props with String data type can get validated by this.
- object: Object type of prop can get validated by this.
- number: Props with Numeric data type can get validated by this.
The above PropTypes can be used while building a react application.
Code:
Component.propTypes = {
numberProp: PropTypes.number,
functionProp: PropTypes.func
anyProp: PropTypes.any,
}
1. Renderable Types
The validators stated below are also exported by PropTypes to ensure that the value being passed can be rendered by React.
a. PropTypes.node: Any prop value such as an array, an element, a string or a number that React can render.
b. PropTypes.element: An element should be used as a Prop.
Code:
Component.propTypes = {
Propnodesyntax: PropTypes.node,
Propelementsyntax: PropTypes.element
}
PropTypes.element is commonly used to ensure a singular child of component. A warning gets displayed whenever there are multiple or no children of the component.
Code:
Component.propTypes = {
singlechild: PropTypes.element.isRequired
}
2. Instance Validators
PropTypes.instanceOf validator is used whenever a prop is to become a specific JavaScript class’s instance. The fundamental instanceof method is leveraged by it.
Code:
Component.propTypes = {
IndividualProp: PropTypes.instanceOf(Individual)
}
3. Multiple Datatype Validators
Validators can also be exported by PropTypes to allow a group of different values or different groups of data types.
The validators used for this purpose are as follows:
a. PropTypes.oneOf: A particular group of values are set in a prop.
b. PropTypes.oneOfType: The prop needs to behave like a union of types and it needs to be from the specified set of types.
Code:
Component.propTypes = {
Propenum: PropTypes.oneOf(
['move',[1,2,3],True]),
Propunion: PropTypes.oneOfType
([
PropType.string,
PropType.array,
PropType.bool,
PropType.object
])
}
4. Collection Datatype Validators
Other than the validators PropTypes.object & thePropTypes.array, there are other types of validators provided by PropTypes. These validators provide more calibrated validation of objects and arrays. The validators which can be used.
5. PropTypes.arrayOfValidator
This validator is used for ensuring the prop to be an array that matches the type which is specified for validating.
Code:
Component.propTypes =
{
GroupArrayProp: PropTypes.arrayOf(
PropTypes.instanceOf(Individual)
),
NumerousArrayProp: PropTypes.arrayOf
(
PropTypes.oneOfType
([
PropType.bool,
PropType.number
])
)
}
6. PropTypes.objectOf Validator
This is used for ensuring the prop to be an object and all the property values should be matching the type specified for validating.
Code:
Component.propTypes =
{
PropObjectString: PropTypes.objectOf
(
PropTypes.string
),
PropObjectMultiple: PropTypes.objectOf
(
PropTypes.oneOfType
([
PropType.bool,
PropType.number,
PropType.func,
])
)
}
7. PropTypes.shape
When we need a more extensive validation then PropTypes.shape is used. It confirms the prop to be an object which holds a specific key set with specific type of values.
Code:
Component.propTypes =
{
BiodataProp: PropTypes.shape
({
isEmployee: PropTypes.bool,
DOJ: PropTypes.instanceOf(Date),
identityNo: PropTypes.number,
Department: PropTypes.string,
Sex: PropTypes.oneOf(['M', 'F']),
})
}
8. PropTypes.exact Validator
To match the objects strictly, PropTypes.exact is used in the following way.
Code:
Component.propTypes =
{
MarksProp: PropTypes.exact({
Language: PropTypes.oneOf
(['Sanskrit', 'Devnagri', 'Gurumukhi']),
score: PropTypes.number
})
}
9. Required Validator
All of the PropTypes we saw till now doesn’t need the prop to be mandatory. Although we can add is required and the time it sees an incorrect prop, the warning message displays.
Code:
Component.propTypes =
{
PropString: PropTypes.string.isRequired,
PropBoolean: PropTypes.bool.isRequired,
PropObject: PropTypes.object.isRequired,
PropArray: PropTypes.array.isRequired,
PropNumeric: PropTypes.number.isRequired,
BiodataProp: PropTypes.shape
({
IdentityNo: PropTypes.number.isRequired,
DOJ: PropTypes.instanceOf(Date).isRequired,
isEmployee: PropTypes.bool
}).isRequired
}
10. Custom Type
There are some occasions where custom validation logics are defined for a component prop. Custom validation is allowed by PropTypes to use it for typechecking.
Basic Examples:
There are three arguments supported by custom validation:
- componentName: This argument contains the component’s name.
- propName: This argument has the prop’s name.
- props: This contains the props which are going to be passed to a component.
Examples of React PropTypes
Given below are the examples mentioned :
Example #1
Basic Example of React Proptypes.
In the example below, PropTypes are imported from prop-types. Here, the major focus is on validating string values using PropTypes.string.isRequired.
index.js
Code:
import React
, { Component } from "react";
import { render } from "react-dom";
import PropTypes from "prop-types";
export default class App extends Component {
render() {
return (
<div>
<h1>Heyoo {this.props.name}</h1>
</div>
);
}
}
App.propTypes = {
name: PropTypes.string.isRequired
};
if (typeof window !== "undefined") {
render(<App name="Buddy!" />, document.getElementById("root"));
}
Output:
Example #2
React PropTypes example with Array, String, Number and Boolean Values.
In the example below, the values like array, string, number and Boolean are validated using this.props.arrayProp, this.props.stringProp, this.props.numberProp, this.props.boolProp respectively.
index.js
Code:
import PropTypes from 'prop-types';
import React from 'react';
import ReactDOM from 'react-dom';
class ComponentExample extends React.Component{
render(){
return(
<div>
{}
<h1>Example of React PropTypes with</h1>
<h2>
Array Example:
{this.props.arrayProp}
<br />
</h2>
<h3>
String Example:
{this.props.stringProp}
<br />
</h3>
<h4>
Number Example:
{this.props.numberProp}
<br />
</h4>
<h5>
Boolean Example (which is set True)
{this.props.boolProp}
<br />
</h5>
</div>
);
}
}
ComponentExample.propTypes = {
arrayProp: PropTypes.array,
stringProp: PropTypes.string,
numberProp: PropTypes.number,
boolProp: PropTypes.bool,
}
ComponentExample.defaultProps = {
numberProp: "15",
stringProp: "EDUCBA",
arrayProp: ['Rahul', 'Adarsh', 'Ankush'],
boolProp: true,
}
ReactDOM.render(
<ComponentExample />,
document.getElementById("root")
);
Output:
Conclusion
On the basis of the above article, we saw PropTypes and its working. We went through the different methods of validating props and the examples above helps in understanding their application.
Recommended Articles
This is a guide to React PropTypes. Here we discuss the introduction to React PropTypes, different PropTypes and their working with respective examples. You may also have a look at the following articles to learn more –