How to use PropTypes for Type-Checking in React Components ?
Last Updated :
01 May, 2024
React is a JavaScript library for building user interfaces, and one of its key features is component-based architecture. When building React components, it's essential to ensure that the data passed to them is of the correct type. PropTypes is a built-in type-checking library in React that helps developers validate the props passed to components during development.
Prerequisites:
What are PropTypes?
PropTypes is a utility library that provides a way to specify the expected data types of props passed to React components. By defining PropTypes for components, developers can catch bugs related to incorrect prop types early during development. PropTypes checks are performed only in development mode, and they help document the expected shape of the data that a component requires.
Syntax:
componentName.propTypes = {
propName : PropTypes.datatype
}
PropTypes Validators
PropTypes provides a variety of validators to check the data type of props. Here are some commonly used PropTypes validators:
PropTypes.string
: Validates that the prop is a string.PropTypes.number
: Validates that the prop is a number.PropTypes.bool
: Validates that the prop is a boolean.PropTypes.array
: Validates that the prop is an array.PropTypes.object
: Validates that the prop is an object.PropTypes.func
: Validates that the prop is a function.PropTypes.node
: Validates that the prop is a React node (i.e., a string
or a ReactElement
).PropTypes.element
: Validates that the prop is a React element.PropTypes.instanceOf(Class)
: Validates that the prop is an instance of the specified class.PropTypes.oneOf(array)
: Validates that the prop is one of the specified values in the array.PropTypes.oneOfType(array)
: Validates that the prop matches one of the specified PropTypes.PropTypes.arrayOf(type)
: Validates that the prop is an array of a specific type.PropTypes.objectOf(type)
: Validates that the prop is an object with values of a specific type.PropTypes.shape({})
: Validates that the prop has a specific shape.
Steps to Create the React Application:
Step1 : Create a new react application using the following command.
npx create-react-app@latest my-app
Step 2: Navigate to the root directory of your folder app using the following command.
cd my-app
Project Structure:

The Updated Dependencies in package.json are as:
"dependencies": {
"react": "^18.2.0",
"react-dom": "^18.2.0",
"react-scripts": "5.0.1",
"web-vitals": "^2.1.4"
}
Validating Data types
To validate whether a received prop is a string or not using PropTypes, you can use the PropTypes.string
validator. This ensures that the prop passed to the component is of type string, providing a simple and effective way to validate data types.
Example : Implementation to showcase the validation of data types using PropTypes.
JavaScript
// App.js
import MyComponent from './myComponent';
function App() {
return (
<div>
<MyComponent name={1} />
</div>
);
}
export default App;
JavaScript
// myComponent.js
import PropTypes from 'prop-types'
function MyComponent({ name }) {
return (
<div>
{name}
</div>
)
}
MyComponent.propTypes = {
name: PropTypes.string
}
export default MyComponent
Step to Run Application:Â Run the application using the following command from the root directory of the project
npm start
Output:Â Your project will be shown in the URL http://localhost:3000/

Explanation: In the above example given, the component "MyComponent" has received a prop of type "number". Although a component can receive props of any type, a warning is being displayed in the console because a rule has been declared (i.e., name: PropTypes.string) that specifies that the received props should be of type "string".
Creating Default props
Default props in React allow you to set fallback values for component properties. This ensures your component has a value to use even if no prop is passed, this helps in preventing unwanted errors.
Default props can be intialized by following the below syntax.
componentName.defaultProps = {
propName : value
};
Example : This example exhibit's the use of Default props and focuses on preventing errors with defaults.
JavaScript
function MyComponent({name}) {
return (
<div>
{name}
</div>
)
}
MyComponent.defaultProps = {
name: 'Default'
};
export default MyComponent;
Output:

Validating Props Class name
To validate whether a prop belongs to a particular class or not using PropTypes, you can use the PropTypes.instanceOf(Class)
validator. This allows you to specify the class that the prop should be an instance of.
Example: This example validates the props class name.
JavaScript
//myComponent.js
import PropTypes from 'prop-types'
class Sample {
constructor(value) {
this.data= value.data;
}
}
function MyComponent({name}) {
return (
<div>
{name}
</div>
)
}
MyComponent.propTypes = {
name: PropTypes.instanceOf(Sample)
};
export default MyComponent;
Output :

Validating multiple values
React PropTypes provides a feature named multiple validation of props, this feature helps in validating either one or more prop values or it's types simultaneously.
Example: Implementation to showcase the validation of multiple values using PropTypes.
JavaScript
// myComponent.js
import PropTypes from 'prop-types'
function MyComponent({ name, value }) {
return (
<div>
<h1>{name}</h1>
<h1>{value}</h1>
</div>
)
}
MyComponent.propTypes = {
name: PropTypes.oneOf([40, 'Sample']),
value: PropTypes.oneOfType([
PropTypes.string,
PropTypes.number
])
};
export default MyComponent;
Output:

Explanation: In the example mentioned above, we are validating two properties, namely "name" and "value". We are checking if the "name" property has any of the two specified values, namely 40 or 'Samples'. As the "name" property does not have either of these values, a warning is generated in the console. However, since the "value" property is of the "number" type, it does not generate any errors.
Exact props validation
PropTypes provides us a feature to validate, that whether we are having the same number of props, are of same order and same type.
Example: Implementation to showcase the exact props validation using PropTypes.
JavaScript
import PropTypes from 'prop-types'
function MyComponent({data}) {
return (
<div >
<h1>{data.name}</h1>
<h1>{data.value}</h1>
</div>
)
}
MyComponent.defaultProps ={
data :({
name : "sanjay",
value : 12,
value2 : 18,
})
}
MyComponent.propTypes = {
data : PropTypes.exact({
name :PropTypes.string,
value : PropTypes.number
})
};
export default MyComponent;
Output:

Conditional type checking
PropTypes provides a feature to perform conditional type checking, it can be done by using a PropType "PropTypes.isRequired".
Example : Suppose we have a requirement that a component should receive at least one prop and that prop must be of number type. In this case we would use "PropType.isRequired".
JavaScript
import PropTypes from 'prop-types'
function MyComponent({value}) {
return (
<div>
<h1>{value}</h1>
</div>
)
}
MyComponent.defaultProps ={
value : 12
}
MyComponent.propTypes = {
value : PropTypes.number.isRequired
};
export default MyComponent;
Output:

Note: It generates a correct output as the requirements are met.
Custom PropTypes
Custom PropTypes enable developers to define their own validation logic for props beyond the built-in PropTypes validators, allowing for specific requirements or constraints enforcement on props passed to React components.
Example: Implementation to showcase the creation of custom props using PropTypes.
JavaScript
import PropTypes from 'prop-types'
function MyComponent({name}) {
return (
<div>
<h1>{name}</h1>
</div>
)
}
MyComponent.defaultProps ={
name : 12
}
MyComponent.propTypes = {
name(props, propName){
if(!/string/.test(props[propName])){
return new Error(`${propName} is not a string type`)
}
}
};
export default MyComponent;
Output:

Explanation: In the previous example, we set the "name" property with an integer value. However, in this new example, we created a custom hook that checks whether the received property is of the "string" type or not. As the received property is not of string type, it throws a warning on the console that says "name is not a string type".
Conclusion
PropTypes is a valuable tool for ensuring the correctness of data passed to React components. By defining PropTypes, developers can catch bugs early in the development process and provide clear documentation about the expected shape of the data. Whether you choose to define PropTypes inline or as static properties, incorporating PropTypes into your React components can improve code quality and maintainability.
Similar Reads
How to use PropTypes in a Functional Component in React?
PropTypes is a mechanism provided by React for type-checking props passed to components. It allows developers to specify the expected types of props (such as strings, numbers, arrays, objects, etc.) and whether they are required or optional. PropTypes helps catch bugs early by providing warnings in
2 min read
How To Pass Props From Parent to Child Component in ReactJS?
ReactJS is a powerful library that helps developers build interactive user interfaces by breaking them into reusable components. One of the essential features of React is the ability to pass data between components using props. In React, props allow parent components to send data or functions to chi
3 min read
How to use HOCs to reuse Component Logic in React ?
In React, making reusable components keeps your code neat. Higher-order components (HOCs) are a smart way to bundle and reuse component logic. HOCs are like magic functions that take a component and give you back an upgraded version with extra powers or information. HOCs can be implemented in a few
4 min read
Different ways to access props inside a Component in React
The props keyword is the shorthand for properties. It is one of the most important features of React which helps in effective communication between various React components. It is a read-only attribute for passing data from the parent component to the child component. There are various ways to acces
4 min read
How to access props.children in a stateless functional component in ReactJS ?
The {props. children} allows you to create a generic template, which can be modified by a parent when invoked. In this way, a parent component can easily pass whatever is necessary to its child, even generated layout features. Anytime you call a component, it automatically displays whatever it has b
5 min read
How to catch props data on component change in Vue.js ?
In this article, we will see how we can pass different data values between components with the help of props in Vue.js along with a basic understanding of props, components, and their syntax with an example. Vue.js is an open-source progressive JavaScript framework for developing user interfaces and
4 min read
How to Test React Components using Jest ?
React is a frontend open-source JavaScript library, used to build interactive User Interfaces. React is focused on Single Page applications and is more popularly known as a SPA. Testing is an important aspect of development. It examines whether the application is behaving as intended, and protects i
6 min read
How to write unit tests for React components?
A React component is a small, reusable piece of code that represents a part of a user interface in a web application. Components can contain their own data, logic, and visual elements, making it easy to build complex user interfaces by combining and nesting them together. To write unit tests for Rea
2 min read
React.js Blueprint Non-ideal state Component Props
BlueprintJS is a React-based UI toolkit for the web. This library is very optimized and popular for building interfaces that are complex data-dense for desktop applications. NonIdealState Component provides a way for users to inform the user that some content is unavailable. There are three types of
3 min read
How To Use React Context In NextJS With Typescript?
React introduced Context to simply managing global consistent states in application. In this article we will how to use React Context for consistent states across various components with Next.js, the most popular and widely used React meta framework, and with TypeScript or complete type safety.Prere
4 min read