DEV Community

sujon554
sujon554

Posted on

3 2

Prop Types

Before the release of React 15.5.0 version prop-Types is available in the react package but in later versions of React have to add a dependency in your project. You can add the dependency in your project by using the command given below:

npm install prop-types --save
Enter fullscreen mode Exit fullscreen mode

Import Elements

  import PropTypes from 'prop-types'
Enter fullscreen mode Exit fullscreen mode

SO we get a something Different type of Prop-Types below:

Basic types

PropTypes.any: The prop can be of any data type
PropTypes.bool: The prop should be a Boolean
PropTypes.number: The prop should be a number
PropTypes.string: The prop should be a string
PropTypes.func: The prop should be a function
PropTypes.array: The prop should be an array
PropTypes.object: The prop should be an object
PropTypes.symbol: The prop should be a symbol

and Here we can example
Component.propTypes = {
anyProp: PropTypes.any,
booleanProp: PropTypes.bool,
numberProp: PropTypes.number,
stringProp: PropTypes.string,
functionProp: PropTypes.func
}

Renderable types

PropTypes also exports the following validators for ensuring that the value passed to a prop can be rendered by React.
Component.propTypes = {
nodeProp: PropTypes.node,
elementProp: PropTypes.element
}

Instance types

In cases where you require a prop to be an instance of a particular JavaScript class, you can use the PropTypes.instanceOf validator. This leverages the underlying JavaScript instanceof operator.

Component.propTypes = {
personProp: PropTypes.instanceOf(Person)
}

Multiple types

PropTypes also exports validators that can allow a limited set of values or multiple sets of data types for a prop. Here they are:

  • PropTypes.oneOf: The prop is limited to a specified set of values, treating it like an enum
  • PropTypes.oneOfType: The prop should be one of a specified set of types, behaving like a union of types

Component.propTypes = {
enumProp: PropTypes.oneOf([true, false, 0, 'Unknown']),
unionProp: PropTypes.oneOfType([
PropType.bool,
PropType.number,
PropType.string,
PropType.instanceOf(Person)
])
}

`*and here also *

Collection types

Required types

Heroku

Build apps, not infrastructure.

Dealing with servers, hardware, and infrastructure can take up your valuable time. Discover the benefits of Heroku, the PaaS of choice for developers since 2007.

Visit Site

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more