defaultProps

propTypes

Objectives

  • Use defaultProps to give props a default value

  • Use propTypes to specify what props a component is expecting

defaultProps

Default values for props in a component

class IngredientList extends Component {
  static defaultProps = {
    ingredients: []
  }

  render() {
    return (
      <ul>
        {this.props.ingredients.map((ing, index) => (
           <li key={index}>{ing}</li>
         ))}
      </ul>
    );
  }
}

defaultProps

This syntax also works

class IngredientList extends Component {
  render() {
    return (
      <ul>
        {this.props.ingredients.map((ing, index) => (
           <li key={index}>{ing}</li>
         ))}
      </ul>
    );
  }
}

IngredientList.defaultProps = {
  ingredients: []
};
class App extends Component {
  static defaultProps = {
    recipes: [{
      title: "Spaghetti",
      ingredients: ["flour", "water"],
      instructions: "Mix ingredients",
      img: "spaghetti.jpg"
    }]
  }
  render() {
    return (
      <div>
        {this.props.recipes.map((r, index) => (
           <Recipe key={index} title={r.title}
                   ingredients={r.ingredients}
                   img={r.img} instructions={r.instructions}
           />
         ))}
      </div>
    );
  }
}
class App extends Component {
  static defaultProps = {
    recipes: [{
      title: "Spaghetti",
      ingredients: ["flour", "water"],
      instructions: "Mix ingredients",
      img: "spaghetti.jpg"
    }]
  }
  render() {
    return (
      <div>
        {this.props.recipes.map((r, index) => (
           <Recipe key={index} {...r} />
         ))}
      </div>
    );
  }
}

PropTypes

Development time type checker for your props

Installation:

npm install --save prop-types

PropTypes

import PropTypes from 'prop-types';

class IngredientList extends Component {
  static propTypes = {
    ingredients: PropTypes.arrayOf(PropTypes.string)
                          .isRequired
  }
  render() {
    return (
      <ul>
        {this.props.ingredients.map((ing, index) => (
           <li key={index}>{ing}</li>
         ))}
      </ul>
    );
  }
}

Facebook PropTypes Docs

Default Props and Prop Types

By Elie Schoppik

Default Props and Prop Types

  • 2,882