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., astring
or aReactElement
).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.
Table of Content
- Validating Data types
- Creating Default props
- Validating Props Class name
- Validating multiple values
- Exact props validation
- Conditional type checking
- Custom PropTypes
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"
}
How to use PropTypes for Type-Checking in React Components ?
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.
Contact Us