Specifying a default for a function component prop

We can provide default values for props where appropriate to simplify the consumption of a component. In this lesson, we'll learn how to do this.

In the CodeSandbox project we were working on in the last lesson, we are going to implement a default value of “How are you?” for the message prop. We are going to implement this in 2 different ways.

defaultProps approach

The first way is to use a static property called defaultProps on the function component. This is set to an object literal that contains the values to set the props to:

Component.defaultProps = {
  prop1: value1,
  prop2: value2,
  ...
}

In our CodeSandbox project, use the defaultProps approach to set the message prop to “How are you?” by default.

Get hands-on with 1200+ tech skills courses.