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
Non-linear Components In electrical circuits, Non-linear Components are electronic devices that need an external power source to operate actively. Non-Linear Components are those that are changed with respect to the voltage and current. Elements that do not follow ohm's law are called Non-linear Components. Non-linear Co
11 min read
JavaScript Tutorial JavaScript is a programming language used to create dynamic content for websites. It is a lightweight, cross-platform, and single-threaded programming language. It's an interpreted language that executes code line by line, providing more flexibility.JavaScript on Client Side: On the client side, Jav
11 min read
Web Development Web development is the process of creating, building, and maintaining websites and web applications. It involves everything from web design to programming and database management. Web development is generally divided into three core areas: Frontend Development, Backend Development, and Full Stack De
5 min read
Spring Boot Tutorial Spring Boot is a Java framework that makes it easier to create and run Java applications. It simplifies the configuration and setup process, allowing developers to focus more on writing code for their applications. This Spring Boot Tutorial is a comprehensive guide that covers both basic and advance
10 min read
React Interview Questions and Answers React is an efficient, flexible, and open-source JavaScript library that allows developers to create simple, fast, and scalable web applications. Jordan Walke, a software engineer who was working for Facebook, created React. Developers with a JavaScript background can easily develop web applications
15+ min read
React Tutorial React is a powerful JavaScript library for building fast, scalable front-end applications. Created by Facebook, it's known for its component-based structure, single-page applications (SPAs), and virtual DOM,enabling efficient UI updates and a seamless user experience.Note: The latest stable version
7 min read
JavaScript Interview Questions and Answers JavaScript is the most used programming language for developing websites, web servers, mobile applications, and many other platforms. In Both Front-end and Back-end Interviews, JavaScript was asked, and its difficulty depends upon the on your profile and company. Here, we compiled 70+ JS Interview q
15+ min read
Class Diagram | Unified Modeling Language (UML) A UML class diagram is a visual tool that represents the structure of a system by showing its classes, attributes, methods, and the relationships between them. It helps everyone involved in a projectâlike developers and designersâunderstand how the system is organized and how its components interact
12 min read
3-Phase Inverter An inverter is a fundamental electrical device designed primarily for the conversion of direct current into alternating current . This versatile device , also known as a variable frequency drive , plays a vital role in a wide range of applications , including variable frequency drives and high power
13 min read
Backpropagation in Neural Network Back Propagation is also known as "Backward Propagation of Errors" is a method used to train neural network . Its goal is to reduce the difference between the modelâs predicted output and the actual output by adjusting the weights and biases in the network.It works iteratively to adjust weights and
9 min read