Open In App

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.

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:

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:

folderstruct

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.

// App.js
import MyComponent from './myComponent';

function App() {
  return (
    <div>
    <MyComponent name={1} />      
    </div>
  );
}

export default App;
// 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/

output-1

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.

function MyComponent({name}) {
  return (
      <div>
        {name}
      </div>
  )
}

MyComponent.defaultProps = {
  name: 'Default'
};

export default MyComponent;

Output:
output-2

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.

//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 :

output-3

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.

// 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:
output-4

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.

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:

output-5

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".

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:
output-6

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.

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:

output-7

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.

Article Tags :