Home » ReactJS PropTypes

ReactJS PropTypes

React props, which stand for “properties”, pass data from one component to another. If a component receives the wrong type of props, it can lead to bugs and unexpected errors in your app.

Since JavaScript does not have a built-in type-checking solution, many developers use extensions such as TypeScript and Flow. However, React has an internal mechanism for props validation called prop types.

We pass different types of information, such as integers, strings, arrays, etc., as props to the components. We can either create default props or pass the props directly as attributes of the components. So, let’s recall how we passed these props to a component.

We passed props from outside a component and used them inside that component. But did we have to check what kind of values we are getting inside our component via props.

It is entirely up to us whether or not we validate the data we receive by using props inside a component. But it is always a good practice for large apps to validate the data we get through props. It will help in debugging and also help in avoiding bugs in the future.

Let us see how to do this.

PropTypes in React

Before React 15.5.0, proptypes are available in the React package, but in later versions of React, you need to add a dependency to your project. You can add a dependency to your project using the below command:

We can use propType to validate any data we get from the prop. But before using it, we have to import it. Add the following line to the top of your index.js file:

Once we have imported propTypes, we are ready to work with them. Like default props, propTypes are also objects where keys are the prop names and values are their types.

Below syntax shows how to use propTypes:

In the above syntax, componentClassName is the name of the component class; Any other type can be any type we are allowed to pass as prop.

A warning will appear on the console for props that do not validate the type of data specified by propTypes. Let’s look at a complete program that uses proptypes for validation for a better understanding:

Javascript

Output:

ReactJS PropTypes

You can see in the above program that we are passing the prop named NumberProp as a string but validating it as a number. You can visit the official documentation of ReactJS to see all the valid types that can take a prop.

Still, everything is rendered perfectly on the browser, but there is a warning message in our browser console. This message tells us that the prop named NumberProp was expected to contain a numeric value, but instead, a string value is passed.

Do React props work?

When you call that component, react props allow you to send data – including numbers, strings, functions, objects, arrays, etc. If you have multiple components, you can pass data from one component to another.

To pass props between components, you would add them when you call the component, just as you would pass arguments when calling a regular JavaScript function.

Why validate props in React?

While developing a React application, you may face the need to structure and define a prop to avoid bugs and errors. Like a function can have mandatory arguments, a react component can require a prop to be defined. Otherwise, it will not render properly.

If you forget to pass a required prop to a component that needs it, it can cause your app to behave unexpectedly.

Consider the following code.

In the above snippet, the component named PercentageStat requires three props for proper rendering: label, score, and total. Default values are set for Score and Total props if they are not provided. The app component renders the percentage position four times, each with different props.

Below is what the app would look like (with some Bootstrap styling):

ReactJS PropTypes

Note that, depending on usage, the label prop is expected to be a string. In the same way, marks and total need to be numerical values as they are used to calculate the percentage. Also, the total is never expected to be 0 because it is being used as the divisor.Below is another code snippet showing a modified app that renders the PercentState components with invalid props.

The app view now looks like this:

ReactJS PropTypes

Using PropTypes in React

PropTypes is React’s internal mechanism for adding type checking to components.

React components use a special property named prop Types to set up type checking.

When props are passed to a React component, they are checked against the type definition configured in the propTypes property. When an invalid value is passed to a prop, a warning is displayed on the JavaScript console.

ReactJS PropTypes

If default props are set for the React component, the value is resolved first before checking against prop types. Therefore, default values are also subject to prop type definitions.

Note that PropTypes type checking happens in development mode, so you can catch bugs in your React application while you’re developing. For performance reasons, it is not triggered in a production environment.

Using the prop-types library in React

Before React 15.5.0, a utility called proptypes was available as part of the React package, which provided several validators for configuring type definitions for component props. It can be accessed with React.PropTypes.

However, in later versions of React, this utility has been moved to a separate package called prop-types, so you will need to add it as a dependency to your project to access the proptypes utility.

It can be imported into your project files as follows:

import propType from ‘prop-type’;

React PropTypes validator

The PropTypes utility exports a wide range of validators for configuring type definitions. Below we’ll list the validators available for basic, renderable, instance, multiple, collection, and required prop types.

Basic types

Below are the validators for the basic data types.

  • PropTypes.any: Prop can be of any data type
  • PropTypes.bool: prop must be a boolean
  • PropTypes.number: prop must be a number
  • PropTypes.string: prop must be a string
  • PropTypes.func: prop must be a function
  • PropTypes.array: prop must be an array
  • PropTypes.object: prop must be an object
  • PropTypes.symbol: prop must be a symbol

Renderable types

PropTypes also exports the following validators to ensure that a value passed to a prop can be provided by React.

  • node: prop must be anything that can be represented by React – a number, string, element, or array (or slice) that contains thesetypes
  • element: prop must be a response element.

A common use of the PropTypes.element validator ensures that a component has only one child. If the component has no children or multiple children, an alert is displayed on the JavaScript console.

Instance types

In cases where you need a prop to be an instance of a particular JavaScript class, you can use the PropTypes.instanceOf validator. It takes advantage of the built-in JavaScript instance of the operator.

Multiple types

PropTypes also exports validators that can allow a limited number of values or multiple sets of data types for a prop. They are here:

  • oneOf: The prop is limited to a specified set of values, treating it likean enum
  • oneOfType: prop must be one of a set of specified types, which behaves like a union of types.

Collection types

In addition to the PropTypes.array and PropTypes.object validators, PropTypes also provides validators for more sophisticated validation of arrays and objects.

PropTypes.arrayOf

PropTypes.arrayOf ensures that prop is an array with all items matching the specified type.

PropTypes.objectOf

PropTypes.objectOf ensures that a prop is an object where all property values match the specified type.

PropTypes.shape

When more detailed validation of an object prop is needed, you can use PropTypes.shape. It ensures that a prop is an object containing a set of specified keys with values of the specified type.

PropTypes.exact

For strict (or exact) object matching, you can use PropTypes.exact as follows:

Required types

The PropTypes validators we’ve explored allow the prop to be optional. However, you can chain isRequired to any prop validator to ensure a warning is shown whenever the prop is not provided.

Custom validators for type-checking React props.

Usually, it will help if you define some custom validation logic for component props – for example, ensuring that a prop is passed a valid email address. Prop-type allows you to define custom validation functions for type checking props.

Native custom validator

The custom validation function takes three arguments:

  • props, an object containing all props passed to the component
  • propname, the name of the prop to be validated
  • Component name, Component name

If the validation fails, it should return an error object. Shouldn’t throw error. Also, console.warn should not be used inside a custom validation function.

ReactJS PropTypes

Custom validation functions can also be used with PropTypes.oneOfType. Here’s a simple example using the isEmail custom validation function in the previous code snippet:

Component will be valid in both of these scenarios:

Custom validators and collections

Custom validation functions can also be used with PropTypes.arrayOf and PropTypes.objectOf. When used this way, the custom validation function is called for each key in the array or object.

However, the custom validation function takes five arguments instead of three:

  • prop value, array, or object itself
  • the key, the key of the current item in the iteration
  • component name component name
  • location, location of valid data (usually “prop”)
  • propFullName, the fully resolved name of the current item being validated. It will be an array [index]; It would be an object to anything. key.

Below is a modified version of the isEmail custom validation function for use with archive types.

All-purpose custom validators

Considering what we learned about custom validation functions, let’s go ahead and create an all-purpose custom validator that can be used as a standalone validator and with collection types.

A slight modification to the isEmail custom validation function will make it an all-purpose validator, as shown below.

Validating Percentage Stat in React

The following code snippet adds prop types to the Percentage Stat component we reviewed at the beginning of this tutorial.

Validate React component props in a production

Debugging a React application can be difficult, especially in a complex situation, if you are interested in monitoring and tracking redux status for all your users in production.

ReactJS PropTypes
ReactJS PropTypes

LogRocket is like a DVR for web apps, recording everything that happens on your site. Instead of guessing why problems occur, you can consolidate and report the status of your application when problems occur.

The LogRocket Redux middleware package adds an extra layer of visibility to your user sessions. LogRocket logs all actions and states from your Redux store.

Type checking with PropTypes

React.PropTypes has moved into a separate package since React v15.5. Please use the prop-type library instead.

We provide a Codemod script to automate the conversion.

As your app grows, you can catch many bugs with type checking. You can use a JavaScript extension such as Flow or TypeScript to test certain applications to test your entire application.

But even if you don’t use them, React has some built-in type checking capabilities. To type check on props for a component, you can assign special propTypes properties:

We’re using a class component in this example, but the same functionality can also be applied to function components or components created by React. PropTypes exports a series of validators that can be used to ensure that the data you receive is valid.

We’re using a class component in this example, but the same functionality can also be applied to function components or components created by React. Memo or response. forwarded.

PropTypes exports a series of validators that can be used to ensure that the data you receive is valid. In this example, we are using PropTypes.string. When an invalid value is supplied for a prop, a warning will be shown in the JavaScript console. For performance reasons, propTypes are only checked in development mode.

PropTypes

Here’s an example documenting the various validators provided:

Requiring Single Child

With PropTypes.element you can specify that only one child can be passed to a component as children.

Default Prop Values

You can define default values for your props by assigning them to a special DefaultProps property:

Using babel transforms such as plugin-proposal-class-properties (previously plugin-transform-class-properties), you can declare default props as static properties within the React component class.

This syntax is not finalized and will require a compilation step to work in a browser. For more information, see Class field proposals.

defaultprops will ensure that this.props.name will have a value if the parent component has not specified it.

propTypes type checking happens after defaultprops are resolved, so type checking will also apply to defaultprops.


You may also like