DefaultProps vs logical OR

I recently started using a reaction, and I tend to define default values ​​as follows:

class TextInput extends Component { render() { return ( <input type="text" name={ this.props.inputName || 'inputName' } style={ this.props.inputStyle || {} } className={ this.props.inputClass || '' } /> ); } } 

instead:

 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 are the disadvantages of this approach compared to using defaultProps ?

+5
source share
2 answers

What are the disadvantages of this approach compared to using defaultProps ?

In your specific code example; none, because you only use one option once. However, imagine larger applications where some support is used in many places, it would be very tedious to manually determine the "fallback value" if the value is false.

Also imagine that suddenly you decide to change this value to something else; You will need to go through your entire component and update wherever this feature is used. This would make him prone to errors and errors.

Another problem with your approach is that if you really do , you want certain support to be false, like null or 0 . Then your state will fail, and a β€œfallback value” will be used instead.


Thus, the use of defaultProps simplifies the management of your props and becomes more comprehensive and manageable.

By the way, for your reference, the logical expression you are using is called Short Circuit Evaluation .

+6
source

Both approaches work correctly. What if you need to use props in several places? Ultimately, you will write logical operations in your code. The default details can be determined once and used without any problems.

However, you can use any method. This is just a coding style question.

+2
source

Source: https://habr.com/ru/post/1269327/


All Articles