DEV Community

Lam Hoang
Lam Hoang

Posted on

Type checking props with PropTypes in React

Use PropTypes

import PropTypes from 'prop-types';

Prop is an optional array

MyComponent.propTypes = {
  optionalArray: PropTypes.array,
};

Prop is an optional boolean

MyComponent.propTypes = {
  optionalBool: PropTypes.bool,
};

Prop is an optional function

MyComponent.propTypes = {
  optionalFunc: PropTypes.func,
};

Prop is an optional number (integer, float…)

MyComponent.propTypes = {
  optionalNumber: PropTypes.number,
};

Prop is an optional object

MyComponent.propTypes = {
  optionalObject: PropTypes.object,
};

Prop is an optional string

MyComponent.propTypes = {
  optionalString: PropTypes.string
};

Prop is an optional symbol

MyComponent.propTypes = {
  optionalSymbol: PropTypes.symbol,
};

Prop is an optional node (numbers, strings, elements, array, fragment)

MyComponent.propTypes = {   optionalNode: PropTypes.node, };

Source: React Cheat Sheet

Top comments (0)