propTypes and defaultProps

propTypes and defaultProps

The great thing about React component is that they let you make reusable chunks of functionality, and share them with other people. But components can get pretty large, and it isn’t always obvious which props you’ll need to supply.

Luckily, React provides a few tools to help.

#propTypes

Each React component can have a special propTypes property that specifies the type of props that it expects to receive.

React will log a warning if you try and create an element with incorrect types.

index.js
import PropTypes from 'prop-types'
import React from 'react'
import ReactDOM from 'react-dom'

function ContactItem(props) {
  return React.createElement('div', {}, /* ... */)
}

ContactItem.propTypes = {
  name: PropTypes.string.isRequired,
  email: PropTypes.string.isRequired,
  photoURL: PropTypes.string,
}

// The supplied props don't match ContactItem's propTypes, so erors
// will be logged to the console.
React.createElement(
  ContactItem,
  {
    name: 'James',
    photoURL: 0,
  }
)
Build In Progress

    Simple, huh? But where did that PropTypes object come from?

    Actually, PropTypes is imported from a separate package, called prop-types. The above editor’s build system is smart enough to download it automatically, but if you’re using Create React App then you’ll need to install it.

    The PropTypes object provides a number of different validators. The example above uses the PropTypes.string.isRequired and PropTypes.string validators, but you can also check for numbers, elements, arrays, and many other types. A full list is available in the official documentation. Or if you want something more compact, you can print out my React Cheatsheet.

    #defaultProps

    React components can also have a special defaultProps property. When you assign an object to defaultProps, React will merge that object with the props provided to createElement() when needed. This comes in handy when you want to provide sensible defaults.

    For example, you could use defaultProps to ensure that a bootstrap-based Button component applies the default when no other color is specified.

    To get a feel for this, try removing the defaultProps from the below example and watching how the console and rendered button changes.

    index.js
    index.html
    import PropTypes from 'prop-types'
    import React from 'react'
    import ReactDOM from 'react-dom'
    
    function Button(props) {
      return (
        <button className={`btn btn-${props.color}`}>
          {props.children}
        </button>
      )
    }
    
    Button.defaultProps = {
      color: 'default',
    }
    
    Button.propTypes = {
      children: PropTypes.node.isRequired,
      color: PropTypes.string.isRequired,
    }
    
    ReactDOM.render(
      <div>
        <Button>Cancel</Button>
        &nbsp;
        <Button color='primary'>Save</Button>
      </div>,
      document.getElementById('root')
    )
    Build In Progress