Default property values work a little differently than default state values. They're set as a class attribute called defaultProps. Let's take a look at a component that declares default property values:
import React, { Component } from 'react';
export default class MyButton extends Component {
// The "defaultProps" values are used when the
// same property isn't passed to the JSX element.
static defaultProps = {
disabled: false,
text: 'My Button'
};
render() {
// Get the property values we want to render.
// In this case, it's the "defaultProps", since
// nothing is passed in the JSX.
const { disabled, text } = this.props;
return <button disabled={disabled}>{text}</button>;
}
}
Why not just set the default property values as an instance property, like you would with default state? The reason is that properties are immutable, and there's no need for them to be kept as an instance property value. State, on the other hand, changes all the time, so the component needs an instance level reference to it.
You can see that this component sets default property values for disabled and text. These values are only used if they're not passed in through the JSX markup used to render the component. Let's go ahead and render this component without any properties, to make sure that the defaultProps values are used:
import React from 'react';
import { render } from 'react-dom';
import MyButton from './MyButton';
// Renders the "MyButton" component, without
// passing any property values.
render(<MyButton />, document.getElementById('root'));
The same principle of always having default state applies with properties. You want to be able to render components without having to know in advance what the dynamic values of the component are.