I recently started using react and I tend to define default values like this:
class TextInput extends Component {
render() {
return (
<input
type="text"
name={ this.props.inputName || 'inputName' }
style={ this.props.inputStyle || {} }
className={ this.props.inputClass || '' }
/>
);
}
}
instead of:
class TextInput extends Component {
render() {
return (
<input
type="text"
name={ this.props.inputName}
style={ this.props.inputStyle}
className={ this.props.inputClass}
/>
);
}
}
TextInput.defaultProps = {
inputName: 'inputName',
inputStyle: {},
inputClass: ''
}
What disadvantages does this approach have in contrast to using defaultProps
?
If you want the default values to be applied for every method, such as the ones from the React life-cycle ( shouldComponentUpdate , etc.) then you must use the defaultProps instead. So, the previous code is actually a mistake that may lead to misunderstanding about the default value of name .
Because defaultProps on functions will eventually get deprecated.
The defaultProps is a React component property that allows you to set default values for the props argument. If the prop property is passed, it will be changed. The defaultProps can be defined as a property on the component class itself, to set the default props for the class.
Default props can be used to define any props that you want to be set for a component, whether or not a value is actually passed in from the parent component. When using default props, you can still override the values specified in the default props object when you pass in values from the parent component.
What disadvantages does this approach have in contrast to using
defaultProps
?
In your particular code example; none, because you are only using each prop once. However, imagine larger applications in which a particular prop is used in many places, it would become very tedious to manually have to define a "fallback value" if the value is falsy.
Also imagine if you suddenly decide to change this value to something different; you would then have to go through your entire component and update everywhere where that particular prop is used. That would make it prone to errors and mistakes.
Another issue with your approach is if you actually do want a particular prop to be falsy, such as null
or 0
. Then your condition would fail and the "fallback value" would be used instead.
So basically, using defaultProps
makes managing your props a bit easier and more comprehensive and manageable.
By the way, for your reference, the logical expression you use is called a Short-circuit evaluation.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With