sleepwalker00
sleepwalker00

Reputation: 53

defaultProps vs logical OR

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?

Upvotes: 5

Views: 194

Answers (2)

Chris
Chris

Reputation: 59511

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.

Upvotes: 7

return007
return007

Reputation: 843

Both approaches work correct. What if you have to use props at multiple places? You will end up writing logical operations everywhere in your code. The default props can be defined once and used without any issues.

However, you can use either way. Its just a matter of coding style.

Upvotes: 2

Related Questions