Reaction PropTypes

How to use PropTypes to set the type of props required

Since JavaScript is a dynamically typed language, we actually have no way to force the types of variables at compile time, and if we pass invalid types, they will fail at runtime, or give weird ones if the types are compatible The result, but what we expected.

Flow andTypescriptCan provide a lot of help, but React can directly help props type, even before running the code, our tools (editor, lints) can also detect when the wrong value is passed:

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

class BlogPostExcerpt extends Component { render() { return ( <div> <h1>{this.props.title}</h1> <p>{this.props.description}</p> </div> ) } }

BlogPostExcerpt.propTypes = { title: PropTypes.string, description: PropTypes.string }

export default BlogPostExcerpt

What types can we use

These are the basic types that we can accept:

  • PropTypes.array
  • PropTypes.bool
  • PropTypes.func
  • PropTypes.number
  • PropTypes.object
  • PropTypes.string
  • PropTypes.symbol

We can accept one of the following two types:

PropTypes.oneOfType([
  PropTypes.string,
  PropTypes.number
]),

We can accept one of many values:

PropTypes.oneOf(['Test1', 'Test2']),

We can accept an instance of a class:

PropTypes.instanceOf(Something)

We can accept any React node:

PropTypes.node

There is not even any type at all:

PropTypes.any

Arrays have a special syntax, we can use it to accept specific types of arrays:

PropTypes.arrayOf(PropTypes.string)

Object, we can use

PropTypes.shape({
  color: PropTypes.string,
  fontSize: PropTypes.number
})

Required attributes

AppendingisRequiredIf this attribute is missing, setting any PropTypes option will cause React to return an error:

PropTypes.arrayOf(PropTypes.string).isRequired,
PropTypes.string.isRequired,

Download mine for freeResponse Handbook


More response tutorials: