12/13 Why do defaultProps work?


#1

Okay, we add this

Button.defaultProps = { text: 'I am a button' };

But why exactly does the Button component take defaultProps as the default source for text?

Is defaultProps a hardcoded default property of all components in React?


#2

our button expects a property text:

      <button>
        {this.props.text}
      </button>

defaultProps is a method we can use to give a default property in case no property is provided, in this case use text because button is expecting a property named text


#3

Thanks, I now managed to find out more info on defaultProps in React’s docs:

You can define default values for your props by assigning to the special defaultProps property […] The defaultProps will be used to ensure that this.props.name will have a value if it was not specified by the parent component. The propTypes typechecking happens after defaultProps are resolved, so typechecking will also apply to the defaultProps.

So it is a special property of React components.


#4

Docs are always a good place to find more information about something

yes, defaultProps is a special property/method of react component to set a default property in case no other properties are provided


#5

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.