Skip to content

Latest commit

 

History

History
53 lines (39 loc) · 1.31 KB

09.PropTypes and DefaultProps.md

File metadata and controls

53 lines (39 loc) · 1.31 KB

Jam3 Lessons - React

PropTypes and DefaultProps

Prop Types

During development React can do type checking for props components are receiving.

The propTypes typechecking happens after defaultProps are resolved, so typechecking will also apply to the defaultProps.

class Lesson extends React.Component {
  constructor(props) {
    super(props);
  }

  render() {
    return (
      <div className="">
        <h2>{this.props.title}</h2>
        <p>{this.props.description}</p>
        <button onClick={ this.props.action }>{ this.props.actionText }</button>
      </div>
    );
  }
}

Lesson.propTypes = {
  title: React.PropTypes.string.isRequired,
  description: React.PropTypes.string,
  action: React.PropTypes.func.isRequired,
  actionText: React.PropTypes.string
};

After specifying the type of the prop you can add isRequired to prevent a component from being instantiated without it.

Default Props

You can also provide a default value for a prop as a fallback.

Lesson.defaultProps = {
  description: 'There is no description for this lesson.'
}

References