What Are Prop-Types In React?

What Is Prop-Types?

The PropTypes tool is used for type-checking in React. This tool checks all the components Props have the correct type or not.

How Prop-Types Is Helpful In React?

Imagine different components send data (props) to each other in large building apps. so, during this development time, Prop get multiple issues, like:

  • Wrong type (type a number instead of a string),
  • missing data when it is required,
  • Not in the correct format.

In this case, React doesn’t stop our app, but Prop-Types will warn us in the console during development time, so we can fix those issues early.

Important note:

  • PropTypes are only checked in development mode, not in production.
  • It is not a replacement for TypeScript or runtime validation libraries. This is a lightweight way to catch mistakes during development.

Why Use PropTypes?

Using PropTypes in React has several key benefits:

  1. Error Prevention: Prop-Types detect mistakes before our app crashes during use. So we don’t face any bugs when the app is running live.
  2. Code Documentation: When we define Prop-Types for our component, it shows us what kind of data (props) the component needs. Using this process, developers can easily understand our code to determine what props to pass between components, without requiring any extra notes or comments.
  3. Improved Debugging: React gives an exact warning in the console when the component receives any wrong type of props. It mentions the component name and prop.
  4. Enhanced Maintainability: Type-checking ensures component patterns when sending and receiving data. This makes your code clean, reliable, and easy to update, especially in large apps.

How To Install PropTypes In React

First, we install PropTypes using this command:

npm install prop-types

Then import PropTypes in the component where you want to use it:

import PropTypes from 'prop-types';

Defining PropTypes in a Component

Let’s understand one real example using Prop-Types. This example shows how we can add PropTypes to the code.

In this code, we have defined the UserProfile React component, which shows the user’s name, age, and membership.

PropTypes specify what type of data component expects to receive as props.

import React from 'react';
import PropTypes from 'prop-types';

function UserProfile({ name, age, isMember }) {
return (
<div>
<h1>Name: {name}</h1>
<p>Age: {age}</p>
<p>{isMember ? "Member" : "Not a member"}</p>
</div>
);
}

UserProfile.propTypes = {
name: PropTypes.string.isRequired,
age: PropTypes.number,
isMember: PropTypes.bool,
};

export default UserProfile;

This Type-checking tells React:

  • name accepts only a string and must be required.
  • age should only be a number, but it is optional.
  • isMember should be a boolean (true or false).

If someone sends name={123} and forgets to send name, React give a warning to you.

Important Types of PropTypes

  • PropTypes.string: Checks if the prop is a string.
  • PropTypes.number: Checks if the prop is a number.
  • PropTypes.bool: Checks if the prop is a boolean.
  • PropTypes.func: Checks if the prop is a function.
  • PropTypes.array: Checks if the prop is an array.
  • PropTypes.object: Checks if the prop is an object.
  • PropTypes.symbol: Checks if the prop is a symbol.
  • PropTypes.node: Checks if the prop can be displayed (string, number, element, or array).
  • PropTypes.element: Checks if the prop is a React element.
  • PropTypes.any: It accepts any data type.

Advanced PropTypes Features

PropTypes provides advanced type-checking options for arrays.

In simple language, the advanced features mean all items match a specific type, like:

1. PropTypes.arrayOf

PropTypes.arrayOf is used when an array should contain a specific data type.

UserProfile.propTypes = {
hobbies: PropTypes.arrayOf(PropTypes.string),
};

//////

<UserProfile hobbies={['Reading', 'Coding']} /> // OK
<UserProfile hobbies={['Reading', 123]} /> // Error: number not allowed

The hobbies prop accepts only a string and an array.

2. PropTypes.oneOf

PropTypes.oneOf ensures that a prop matches one of several specified values.

UserProfile.propTypes = {
membershipType: PropTypes.oneOf(['basic', 'premium', 'vip']),
};

//////

<UserProfile membershipType="vip" /> // OK
<UserProfile membershipType="free" /> // This value is not allowed

The membershipType prop should be exactly match this values: ‘basic’, ‘premium’, or ‘vip’.

3. PropTypes.shape

PropTypes.shape is used to validate objects with specific properties.

UserProfile.propTypes = {
address: PropTypes.shape({
street: PropTypes.string.isRequired,
city: PropTypes.string.isRequired,
postalCode: PropTypes.number,
}),
};

This field only allowed a complete address structure.

4. PropTypes.oneOfType

PropTypes.oneOfType allows for multiple types for a single prop, useful when a prop can take on multiple types.

UserProfile.propTypes = {
id: PropTypes.oneOfType([PropTypes.string, PropTypes.number]),
};

React will accept both a string and a number, but not allow a Boolean value.

Default Props

PropTypes can also use default props, which means it sets a default value if it is not provided. this function prevents errors when required props are missing.

UserProfile.defaultProps = {
age: 18,
isMember: false,
};

If age or isMember is not provided, it sets the default value to 18 and false.

UserProfileCard Example with Full PropTypes

This is a complete Example of Type-Checking:

import React from 'react';
import PropTypes from 'prop-types';

function UserProfileCard({ userInfo }) {
return (
<div style={{ border: '1px solid #ccc', padding: '15px', width: '300px' }}>
<h2>{userInfo.fullName}</h2>
<p>Age: {userInfo.age}</p>
<p>Status: {userInfo.isPremium ? 'Premium Member' : 'Free Member'}</p>

<h4>Skills:</h4>
<ul>
{userInfo.skills && userInfo.skills.map((skill, i) => (
<li key={i}>{skill}</li>
))}
</ul>

<p>Location: {userInfo.location?.city}, {userInfo.location?.country}</p>
</div>
);
}

UserProfileCard.propTypes = {
userInfo: PropTypes.shape({
fullName: PropTypes.string.isRequired,
age: PropTypes.number.isRequired,
isPremium: PropTypes.bool.isRequired,
skills: PropTypes.arrayOf(PropTypes.string),
location: PropTypes.shape({
city: PropTypes.string.isRequired,
country: PropTypes.string.isRequired,
}).isRequired
}).isRequired
};

export default UserProfileCard;

This code requires and accepts only a specific type. If any wrong information is entered, it will give you an error.

Leave a Comment

BoxofLearn