What are React PropTypes and why should I use them?
React PropTypes are a type-checking feature for React components that help validate the types of props passed to a component. They ensure that the correct data types are used, which helps prevent bugs such as rendering errors when, for example, a string is passed instead of a number. PropTypes are checked only in development mode and throw warnings in the browser console if validation fails. Note: PropTypes do not enforce types at runtime in production; for static type checking, consider TypeScript. Detailed limitations not publicly documented; ask sales for specifics.
How do I install and use PropTypes in a React project?
To use PropTypes, install the prop-types package with npm install prop-types --save. Then, import PropTypes into your component and define the expected types for each prop using the ComponentName.propTypes object. For example: Profile.propTypes = { name: PropTypes.string.isRequired, age: PropTypes.number }. PropTypes are only checked in development mode. Note: PropTypes do not replace static type systems like TypeScript.
What types of validations can PropTypes perform?
PropTypes can validate basic types (string, number, object, array, boolean, function, symbol), enforce required props, limit values using oneOf, allow multiple types with oneOfType, validate arrays and objects with arrayOf and objectOf, and define object shapes with shape or exact. You can also create custom validators for advanced use cases, such as email validation. Note: PropTypes only warn in development and do not enforce types at runtime in production.
How do PropTypes compare to TypeScript for type checking in React?
PropTypes provide runtime type checking in development mode only, issuing warnings in the browser console if props do not match the expected types. TypeScript, on the other hand, offers static type checking at compile time, catching errors before code runs. PropTypes are easier to add to existing JavaScript projects, while TypeScript requires a build step and type annotations throughout your codebase. Choose PropTypes for lightweight validation or TypeScript for comprehensive type safety. Note: PropTypes do not prevent runtime errors in production.
Can you provide a real-world example of using PropTypes with Hygraph content?
Yes. In a React project that fetches content from Hygraph (e.g., a cocktail app), you can use PropTypes to validate the shape of product data received from the CMS. For example, Product.propTypes = { product: PropTypes.object.isRequired } ensures that the product prop is an object. For more granular validation, use PropTypes.shape to specify required fields like name, category, info, ingredients, and instructions. See the GitHub repository for a full example. Note: PropTypes only validate in development mode.
Hygraph Platform Features & Capabilities
What is Hygraph and what problems does it solve?
Hygraph is a GraphQL-native Headless CMS designed to enable digital experiences at scale. It addresses operational inefficiencies (such as developer dependency and legacy tech stacks), financial challenges (like high operational costs and slow speed-to-market), and technical issues (including complex schema evolution, integration difficulties, and performance bottlenecks). Hygraph empowers non-technical users to manage content, integrates multiple data sources, and supports global content delivery. Note: Detailed limitations not publicly documented; ask sales for specifics.
What are the key features and benefits of Hygraph?
Key features of Hygraph include a GraphQL-native architecture, content federation (integrating multiple data sources without duplication), enterprise-grade security and compliance (SOC 2 Type 2, ISO 27001, GDPR), Smart Edge Cache, localization, granular permissions, and a user-friendly interface for non-technical users. Hygraph also offers high-performance endpoints, extensive integration options, and structured onboarding. Note: Best fit for teams seeking GraphQL and content federation; teams needing a traditional monolithic CMS may want to consider alternatives.
What integrations does Hygraph support?
Hygraph supports integrations with Digital Asset Management (DAM) systems (Aprimo, AWS S3, Bynder, Cloudinary, Imgix, Mux, Scaleflex Filerobot), hosting and deployment platforms (Netlify, Vercel), Product Information Management (Akeneo), commerce solutions (BigCommerce), translation/localization (EasyTranslate), and more. For a full list, visit the Hygraph Marketplace. Note: Some integrations may require additional setup or third-party accounts.
What APIs does Hygraph provide?
Hygraph offers several APIs: the GraphQL Content API (for querying and manipulating content), the Management API (for project structure management), the Asset Upload API (for uploading files), and the MCP Server API (for secure communication with AI assistants). Each API is documented in detail in the API Reference documentation. Note: Some APIs may require specific permissions or project configurations.
How does Hygraph perform in terms of speed and reliability?
Hygraph is optimized for high performance, with low-latency, high-throughput content delivery via its high-performance endpoints. The read-only cache endpoint provides a 3-5x latency improvement. Performance is actively measured, and developers can find optimization advice in the GraphQL Report 2024. Note: Actual performance may vary based on project complexity and integration setup.
Security, Compliance & Support
What security and compliance certifications does Hygraph have?
Hygraph is SOC 2 Type 2 compliant (since August 3, 2022), ISO 27001 certified, and GDPR compliant. The platform also adheres to the German Data Protection Act (BDSG) and the German Telemedia Act (TMG). All endpoints use SSL certificates, and data is encrypted in transit and at rest. Note: For the latest certification status, visit the Hygraph Secure Features page.
What support and onboarding resources does Hygraph provide?
Hygraph offers structured onboarding (introduction calls, account provisioning, technical kickoffs), extensive documentation, starter projects, webinars, live streams, and community support via Slack. Customers can sign up for a free account and access guides at Hygraph Documentation. Note: Some resources may require registration or a paid plan.
Implementation, Use Cases & Customer Success
How long does it take to implement Hygraph?
Implementation time varies by project complexity. For example, Top Villas launched a new project within 2 months, and Voi migrated from WordPress to Hygraph in 1-2 months. Starter projects and structured onboarding help accelerate adoption. Note: Large-scale or highly customized projects may require additional time.
Who uses Hygraph and what industries does it serve?
Hygraph is used by companies such as Samsung, Dr. Oetker, Komax, AutoWeb, BioCentury, Voi, HolidayCheck, and Lindex Group. Industries represented include SaaS, marketplace, education technology, media, healthcare, consumer goods, automotive, technology, fintech, travel, food and beverage, eCommerce, agency, online gaming, events, government, consumer electronics, engineering, and construction. Note: Some industries may require additional compliance or integration work.
What business impact can customers expect from using Hygraph?
Customers have achieved measurable results, such as Komax realizing a 3x faster time-to-market, Samsung improving customer engagement by 15%, AutoWeb increasing website monetization by 20%, and Voi scaling multilingual content across 12 countries. For more, see Hygraph case studies. Note: Results may vary based on implementation and use case.
Ease of Use & Customer Feedback
What feedback have customers given about Hygraph's ease of use?
Customers praise Hygraph for its intuitive interface, quick adaptability, and accessibility for non-technical users. For example, Sigurður G. (CTO) noted the UI is intuitive, Anastasija S. highlighted instant front-end updates, and Charissa K. described the UI as fast to comprehend and localizable. Granular roles and permissions also streamline workflows. Note: Some advanced features may require technical expertise.
Documentation & Learning Resources
Where can I find technical documentation for Hygraph?
Technical documentation is available at hygraph.com/docs, covering API reference, schema components, getting started guides, integration documentation (e.g., Mux, Akeneo, Auth0), and AI features. Classic documentation is also available for legacy users. Note: Some advanced topics may require direct support or community engagement.
In this article, you will learn what ''PropTypes'' means, how it works, and the various validators you can use to validate your props.
Last updated by Joel
on Jan 21, 2026
Originally written by Joel
When working with React components, you sometimes need to pass props from a parent to a child component. When passing down these props, you may make mistakes and cause bugs that are hard to detect by passing in values as a wrong data type. For example, if you are expected to pass an age prop which should be a number, you mistakenly passed the number as a string.
import{Profile}from'./Profile';
exportconstApp=()=>{
let user ={name:'John Doe',age:'23'};
return<Profile userDetails={user}/>;
};
If you want to maybe add to the age in the Profile component, it affects what will render on your React application. Also, unfortunately, React won’t throw an error; instead, it will render this as a concatenation.
exportconstProfile=({ userDetails })=>{
return(
<p>
{userDetails.name} is {userDetails.age+3}
years old
</p>
);
};
On the webpage, 233 years is rendered instead of 26 years because 23 was mistakenly passed in as a string. How about there is a way for you to check and validate each prop type that comes into a child component so it matches what you are expecting; else, it throws an error in your browser’s console.
By default, JavaScript does not have a built-in type-checking solution, so Microsoft introduced TypeScript. However, React has an internal method that you can use for props validation known as PropTypes.
In this article, you will learn what PropTypes is about, how it works, and when to use it. You will also learn the various types of PropTypes and, finally, see how it works with a real-world example that fetches content from Hygraph CMS.
As your React application grows, you’d become more intentional about the props you pass. You will want to ensure some props are required, set default values, and give props more validation power.
PropTypes serves as the method you can use to ensure the correct datatype is passed for each prop, meaning whatever is rendered is correct. It can also be used to ensure a value is passed, set default values, and lots more.
In plain terms, it is used as a validator to ensure the data your component receives is valid. There are many different types of PropTypes, and all have unique ES6 classes, which you can use.
Note: The significant difference between TypeScript and PropTypes is that propTypes is only checked in development mode while TypeScript performs these checks from your code environment.
If you don’t understand props well and what it means in React, let’s do a quick dive, so you can perfectly understand this article.
A prop is a short form for “properties”. You can use it to pass down data from a parent component to a child component. For example, if you fetch a list of products from an external in the App.js component, you also want to use these same products in a child component. Instead of having to fetch or pass the data again, you can pass down the data easily.
When working with functions, you would pass in arguments, which, when these arguments are not passed, will throw an error or break your application. This also applies to React component; you will sometimes want to pass required prop(s) or validate the datatype of each prop because failure to pass in the correct prop will affect your application’s behavior. You can do all these with PropTypes.
Also, when working on large applications for clients and with a team, it is always good to validate these props to avoid unexpected production bugs.
How to use PropTypes
Previously, before the release of React v15.5, PropTypes was inbuilt into the React package, but now it has been moved into a different package which you will first have to install into your project to make use of it.
You can install it in your project by running the following command in your terminal:
$ npm install prop-types --save
Once it has been installed, you will first have to import it into whichever component you want to use to access its features.
importPropTypesfrom'prop-types';
When you import it into your component, you can now attach the component name to the PropTypes method and create an object containing all your prop's validation.
importPropTypesfrom'prop-types';
exportconstProfile=(props)=>{
return(
<p>
{props.name} is {props.age+3}
years old
</p>
);
};
Profile.propTypes={
// Props validations here
};
Your PropTypes object will contain key-value pairs for each prop you validate, the key is the prop's name, and the value is the PropTypes validation (the type and other validation). Let's now explore the various Prop types with examples.
The PropTypes method holds a wide range of classes that you can use to validate and configure type definitions. These types will be grouped into sections, so they are easy to understand.
Basic types
The basic types are the regular data types you always use in JavaScript. This includes string, number, object, array, boolean, function, and symbol. You can only use them by attaching the PropTypes method.
ComponentName.propTypes={
anyValue:PropTypes.any,// the prop can be of any data type
myString:PropTypes.string,// prop should be a string
myNumber:PropTypes.number,// prop should be a number
myObject:PropTypes.object,// prop should be an object
myArray:PropTypes.array,// prop should be an array
myBoolean:PropTypes.bool,// prop should be boolean
myFunction:PropTypes.func,// prop should be a function
mySymbol:PropTypes.symbol,// prop should be a symbol
};
For example, if you pass three props which are name, age, and isLoggedIn, then you can configure their types:
importPropTypesfrom'prop-types';
exportconstProfile=({ name, age, isloggedIn })=>{
return(
<>
{isloggedIn &&(
<p>
{name} is {age +3}
years old
</p>
)}
</>
);
};
Profile.propTypes={
name:PropTypes.string,
age:PropTypes.number,
isloggedIn:PropTypes.bool,
};
You can make a prop required by attaching .isRequired, meaning when the prop is not passed, it will throw an error in our console.
Profile.propTypes={
name:PropTypes.string.isRequired,
age:PropTypes.number.isRequired,
isloggedIn:PropTypes.bool.isRequired,
};
When you don’t pass a particular prop, you will get an error like this in your console:
Multiple types
PropTypes can also allow you to set the type of values your props should be and the expected value. It allows you to set a limited set of values or multiple data types for a prop. This can be done using PropTypes.oneOf() and PropTypes.oneOfType() validators. These validators take in an array.
PropTypes.oneOf(): This validator can be used to set limited values for a prop. For example, if you want the value of your name prop to be either “John” or “Jane”. You can achieve this with this validator.
Profile.propTypes={
name:PropTypes.oneOf(['John','Jane']).isRequired,
// ...
};
This means when you pass in another value asides from “John” and “Jane” to the name prop, it will throw an error:
PropTypes.oneOfType(): Just like you can set limited values for your prop, you can also set multiple datatypes for your prop, meaning if you want a prop value to either be an array or object, you can set it with this validator.
Passing a value that may be a string to the arrayOrObject prop will throw an error to your console.
Collective types
You now know how these PropTypes work, and you have seen the basic types, similar to the regular data types in programming. Some other types help you validate more advanced types of props.
Array
Asides from PropTypes.array validator, which you can use for array types, PropTypes uses the PropTypes.arrayOf() validator to perform more fine-tuned validation of arrays. This method allows you to check the type of values in an array.
For example, your component might expect a prop with an array of numbers, and then you can use PropTypes.arrayOf() to validate only numbers.
In the code above, myObject prop will only accept an object with values that are string, such as:
myObject:{
pet:'cat',
food:'pizza',
},
When you maybe have a number as its value or introduce a new key-value pair such as age: 10, it will throw an error in your console.
Two other validators work with objects. These validators help you validate the type for each value in an object and can also help make the object closed, meaning when you add another key-value pair whose type is not declared it will throw an error. These two validators are:
PropTypes.shape(): This can be used to define a set of keys for an object and validate its data types. For example, if an object consists of name, age, and id, then you can validate the type for each key.
Profile.propTypes={
userDetails:PropTypes.shape({
id:PropTypes.number.isRequired,
name:PropTypes.string.isRequired,
age:PropTypes.number.isRequired,
}),
};
This means that when you pass a string as the age value, it will throw an error. When you define all these validations for each key in an object, you will notice that when you define a new key-value pair, you can use it within your application without validating its type. You can fix this using the PropTypes.exact() validator.
PropTypes.exact(): This validator can be used for strict or exact object matching. This means that it will throw an error when you have extra properties in the object you are validating:
Profile.propTypes={
userDetails:PropTypes.exact({
id:PropTypes.number,
name:PropTypes.string,
age:PropTypes.number,
}).isRequired,
};
Advanced type checking for components and component names
In some scenarios, you might have to pass in a component as a prop. To check if a prop is a component, you can use the PropTypes.element validator.
Component.propTypes={
elementProp:PropTypes.element
}
One significant advantage and common use for the PropTypes.element validator is to ensure that a component has only one child. If the component has no children or multiple children, it will display a warning on the JavaScript console.
Component.propTypes={
children:PropTypes.element.isRequired
}
Custom types
You have learned how to validate props with the default validators, but how about creating your validators. Suppose you want to validate the value of a prop to be sure it matches what you expect— maybe an email value.
You can do this by creating a custom validator. To create a custom validator, you will create a function that can take in three arguments which are:
props: The original object containing all the props passed to the component
propName: The name of the prop you want to validate
componentName: The name of the component
In the function, you can maybe use a regex to test if the value is an actual email, check for the length, and lots more, and then throw an error if the validation fails using new Error().
Profile.propTypes={
userDetails:PropTypes.shape({
// ...
email:function(props, propName, componentName){
const regex =/^[\w-.]+@([\w-]+\.)+[\w-]{2,4}$/g;
if(!regex.test(props[propName])){
returnnewError(
`The prop ${propName} passed to ${componentName}is not a valid email address.`
);
}
},
}),
};
When you pass in a wrong email value, it will throw the error. You can also decide to extract the validator into a function, so your propTypes object is neat and easy to maintain.
`The prop ${propName} passed to ${componentName}is not a valid email address.`
);
}
};
Profile.propTypes={
userDetails:PropTypes.shape({
id:PropTypes.number,
name:PropTypes.string,
age:PropTypes.number,
email: isEmail,
}),
};
Setting the default prop value
So far, you have learned how to validate props, configure PropTypes, and lots more. It is also important to know that you can set a default value for each prop. You can do this similarly to how PropTypes work but this time, you would use defaultProps (there is no need to import it).
Profile.defaultProps={
userDetails:{
id:1,
name:'John Doe',
age:30,
},
};
Note: This will only work when you fail to pass in the userDetails prop to the component.
Let’s now use PropTypes validators in a real-life project to see how it works. Here is the source code for the project (a cocktail app that fetches content from Hygraph). On the Products.jsx page, which lists all available cocktails, the array is looped, and each object is passed as a prop to the Product.Jsx component.
On the Product.jsx component, the object is validated with the PropTypes.object.
Also, on the ProductDetails.jsx page, you will notice an object is passed into the CocktailInfo.jsx component, where each object value is validated using PropTypes.shape().
In this article, you have learned what PropTypes means, how it works, and the various validators you can use to validate your props.
Have fun coding!
Blog Author
Joel Olawanle
Joel Olawanle is a Frontend Engineer and Technical writer based in Nigeria who is interested in making the web accessible to everyone by always looking for ways to give back to the tech community. He has a love for community building and open source.
Share with others
Sign up for our newsletter!
Be the first to know about releases and industry news and insights.
In this article, you will learn what ''PropTypes'' means, how it works, and the various validators you can use to validate your props.
Last updated by Joel
on Jan 21, 2026
Originally written by Joel
When working with React components, you sometimes need to pass props from a parent to a child component. When passing down these props, you may make mistakes and cause bugs that are hard to detect by passing in values as a wrong data type. For example, if you are expected to pass an age prop which should be a number, you mistakenly passed the number as a string.
import{Profile}from'./Profile';
exportconstApp=()=>{
let user ={name:'John Doe',age:'23'};
return<Profile userDetails={user}/>;
};
If you want to maybe add to the age in the Profile component, it affects what will render on your React application. Also, unfortunately, React won’t throw an error; instead, it will render this as a concatenation.
exportconstProfile=({ userDetails })=>{
return(
<p>
{userDetails.name} is {userDetails.age+3}
years old
</p>
);
};
On the webpage, 233 years is rendered instead of 26 years because 23 was mistakenly passed in as a string. How about there is a way for you to check and validate each prop type that comes into a child component so it matches what you are expecting; else, it throws an error in your browser’s console.
By default, JavaScript does not have a built-in type-checking solution, so Microsoft introduced TypeScript. However, React has an internal method that you can use for props validation known as PropTypes.
In this article, you will learn what PropTypes is about, how it works, and when to use it. You will also learn the various types of PropTypes and, finally, see how it works with a real-world example that fetches content from Hygraph CMS.
As your React application grows, you’d become more intentional about the props you pass. You will want to ensure some props are required, set default values, and give props more validation power.
PropTypes serves as the method you can use to ensure the correct datatype is passed for each prop, meaning whatever is rendered is correct. It can also be used to ensure a value is passed, set default values, and lots more.
In plain terms, it is used as a validator to ensure the data your component receives is valid. There are many different types of PropTypes, and all have unique ES6 classes, which you can use.
Note: The significant difference between TypeScript and PropTypes is that propTypes is only checked in development mode while TypeScript performs these checks from your code environment.
If you don’t understand props well and what it means in React, let’s do a quick dive, so you can perfectly understand this article.
A prop is a short form for “properties”. You can use it to pass down data from a parent component to a child component. For example, if you fetch a list of products from an external in the App.js component, you also want to use these same products in a child component. Instead of having to fetch or pass the data again, you can pass down the data easily.
When working with functions, you would pass in arguments, which, when these arguments are not passed, will throw an error or break your application. This also applies to React component; you will sometimes want to pass required prop(s) or validate the datatype of each prop because failure to pass in the correct prop will affect your application’s behavior. You can do all these with PropTypes.
Also, when working on large applications for clients and with a team, it is always good to validate these props to avoid unexpected production bugs.
How to use PropTypes
Previously, before the release of React v15.5, PropTypes was inbuilt into the React package, but now it has been moved into a different package which you will first have to install into your project to make use of it.
You can install it in your project by running the following command in your terminal:
$ npm install prop-types --save
Once it has been installed, you will first have to import it into whichever component you want to use to access its features.
importPropTypesfrom'prop-types';
When you import it into your component, you can now attach the component name to the PropTypes method and create an object containing all your prop's validation.
importPropTypesfrom'prop-types';
exportconstProfile=(props)=>{
return(
<p>
{props.name} is {props.age+3}
years old
</p>
);
};
Profile.propTypes={
// Props validations here
};
Your PropTypes object will contain key-value pairs for each prop you validate, the key is the prop's name, and the value is the PropTypes validation (the type and other validation). Let's now explore the various Prop types with examples.
The PropTypes method holds a wide range of classes that you can use to validate and configure type definitions. These types will be grouped into sections, so they are easy to understand.
Basic types
The basic types are the regular data types you always use in JavaScript. This includes string, number, object, array, boolean, function, and symbol. You can only use them by attaching the PropTypes method.
ComponentName.propTypes={
anyValue:PropTypes.any,// the prop can be of any data type
myString:PropTypes.string,// prop should be a string
myNumber:PropTypes.number,// prop should be a number
myObject:PropTypes.object,// prop should be an object
myArray:PropTypes.array,// prop should be an array
myBoolean:PropTypes.bool,// prop should be boolean
myFunction:PropTypes.func,// prop should be a function
mySymbol:PropTypes.symbol,// prop should be a symbol
};
For example, if you pass three props which are name, age, and isLoggedIn, then you can configure their types:
importPropTypesfrom'prop-types';
exportconstProfile=({ name, age, isloggedIn })=>{
return(
<>
{isloggedIn &&(
<p>
{name} is {age +3}
years old
</p>
)}
</>
);
};
Profile.propTypes={
name:PropTypes.string,
age:PropTypes.number,
isloggedIn:PropTypes.bool,
};
You can make a prop required by attaching .isRequired, meaning when the prop is not passed, it will throw an error in our console.
Profile.propTypes={
name:PropTypes.string.isRequired,
age:PropTypes.number.isRequired,
isloggedIn:PropTypes.bool.isRequired,
};
When you don’t pass a particular prop, you will get an error like this in your console:
Multiple types
PropTypes can also allow you to set the type of values your props should be and the expected value. It allows you to set a limited set of values or multiple data types for a prop. This can be done using PropTypes.oneOf() and PropTypes.oneOfType() validators. These validators take in an array.
PropTypes.oneOf(): This validator can be used to set limited values for a prop. For example, if you want the value of your name prop to be either “John” or “Jane”. You can achieve this with this validator.
Profile.propTypes={
name:PropTypes.oneOf(['John','Jane']).isRequired,
// ...
};
This means when you pass in another value asides from “John” and “Jane” to the name prop, it will throw an error:
PropTypes.oneOfType(): Just like you can set limited values for your prop, you can also set multiple datatypes for your prop, meaning if you want a prop value to either be an array or object, you can set it with this validator.
Passing a value that may be a string to the arrayOrObject prop will throw an error to your console.
Collective types
You now know how these PropTypes work, and you have seen the basic types, similar to the regular data types in programming. Some other types help you validate more advanced types of props.
Array
Asides from PropTypes.array validator, which you can use for array types, PropTypes uses the PropTypes.arrayOf() validator to perform more fine-tuned validation of arrays. This method allows you to check the type of values in an array.
For example, your component might expect a prop with an array of numbers, and then you can use PropTypes.arrayOf() to validate only numbers.
In the code above, myObject prop will only accept an object with values that are string, such as:
myObject:{
pet:'cat',
food:'pizza',
},
When you maybe have a number as its value or introduce a new key-value pair such as age: 10, it will throw an error in your console.
Two other validators work with objects. These validators help you validate the type for each value in an object and can also help make the object closed, meaning when you add another key-value pair whose type is not declared it will throw an error. These two validators are:
PropTypes.shape(): This can be used to define a set of keys for an object and validate its data types. For example, if an object consists of name, age, and id, then you can validate the type for each key.
Profile.propTypes={
userDetails:PropTypes.shape({
id:PropTypes.number.isRequired,
name:PropTypes.string.isRequired,
age:PropTypes.number.isRequired,
}),
};
This means that when you pass a string as the age value, it will throw an error. When you define all these validations for each key in an object, you will notice that when you define a new key-value pair, you can use it within your application without validating its type. You can fix this using the PropTypes.exact() validator.
PropTypes.exact(): This validator can be used for strict or exact object matching. This means that it will throw an error when you have extra properties in the object you are validating:
Profile.propTypes={
userDetails:PropTypes.exact({
id:PropTypes.number,
name:PropTypes.string,
age:PropTypes.number,
}).isRequired,
};
Advanced type checking for components and component names
In some scenarios, you might have to pass in a component as a prop. To check if a prop is a component, you can use the PropTypes.element validator.
Component.propTypes={
elementProp:PropTypes.element
}
One significant advantage and common use for the PropTypes.element validator is to ensure that a component has only one child. If the component has no children or multiple children, it will display a warning on the JavaScript console.
Component.propTypes={
children:PropTypes.element.isRequired
}
Custom types
You have learned how to validate props with the default validators, but how about creating your validators. Suppose you want to validate the value of a prop to be sure it matches what you expect— maybe an email value.
You can do this by creating a custom validator. To create a custom validator, you will create a function that can take in three arguments which are:
props: The original object containing all the props passed to the component
propName: The name of the prop you want to validate
componentName: The name of the component
In the function, you can maybe use a regex to test if the value is an actual email, check for the length, and lots more, and then throw an error if the validation fails using new Error().
Profile.propTypes={
userDetails:PropTypes.shape({
// ...
email:function(props, propName, componentName){
const regex =/^[\w-.]+@([\w-]+\.)+[\w-]{2,4}$/g;
if(!regex.test(props[propName])){
returnnewError(
`The prop ${propName} passed to ${componentName}is not a valid email address.`
);
}
},
}),
};
When you pass in a wrong email value, it will throw the error. You can also decide to extract the validator into a function, so your propTypes object is neat and easy to maintain.
`The prop ${propName} passed to ${componentName}is not a valid email address.`
);
}
};
Profile.propTypes={
userDetails:PropTypes.shape({
id:PropTypes.number,
name:PropTypes.string,
age:PropTypes.number,
email: isEmail,
}),
};
Setting the default prop value
So far, you have learned how to validate props, configure PropTypes, and lots more. It is also important to know that you can set a default value for each prop. You can do this similarly to how PropTypes work but this time, you would use defaultProps (there is no need to import it).
Profile.defaultProps={
userDetails:{
id:1,
name:'John Doe',
age:30,
},
};
Note: This will only work when you fail to pass in the userDetails prop to the component.
Let’s now use PropTypes validators in a real-life project to see how it works. Here is the source code for the project (a cocktail app that fetches content from Hygraph). On the Products.jsx page, which lists all available cocktails, the array is looped, and each object is passed as a prop to the Product.Jsx component.
On the Product.jsx component, the object is validated with the PropTypes.object.
Also, on the ProductDetails.jsx page, you will notice an object is passed into the CocktailInfo.jsx component, where each object value is validated using PropTypes.shape().
In this article, you have learned what PropTypes means, how it works, and the various validators you can use to validate your props.
Have fun coding!
Blog Author
Joel Olawanle
Joel Olawanle is a Frontend Engineer and Technical writer based in Nigeria who is interested in making the web accessible to everyone by always looking for ways to give back to the tech community. He has a love for community building and open source.
Share with others
Sign up for our newsletter!
Be the first to know about releases and industry news and insights.