I am making an autocomplete component which does live search. These are its props:
<AutoCompleteInput
ref={autocomplete.tag}
tag={autocomplete.tag}
type={autocomplete.type}
title={autocomplete.title}
required={autocomplete.required}
photoRequired={autocomplete.photoRequired}
defaultValue={autocomplete.defaultValue}
options={autocomplete.options}
titleKey={autocomplete.titleKey}
valueKey={autocomplete.valueKey}
singleSelection={false}
maxSuggestionNumber={50}
minimumCharacterNumber={-2}
/>
singleSelection, maxSuggestionNumber and minimumCharacterNumber are optional props. I want to give default values to them and also I should check their prop values. For example; default value of minimumCharacterNumber should be '0', so if we dont use that prop, '0' value should be passed into the component. But, if that value is given lower than 0, the component should use default value which is '0'.
I tried the function
public static defaultProps() { ...... }
, but I confused and couldn't handle it with conditions.
What is its ordinary technique ? Any solution will be appriciated.
EDIT: I solved my issue, and I want to share.
public static defaultProps = {
minimumCharacterNumber: 0,
maxSuggestionNumber: 50,
singleSelection: false,
}
constructor(props: ACModalProps) {
super(props)
this.state = {
maxSuggestionNumber:
this.props.maxSuggestionNumber && this.props.maxSuggestionNumber > 0
? this.props.maxSuggestionNumber
: ACModal.defaultProps.maxSuggestionNumber,
minimumCharacterNumber:
this.props.minimumCharacterNumber && this.props.minimumCharacterNumber > 0
? this.props.minimumCharacterNumber
: ACModal.defaultProps.minimumCharacterNumber,
singleSelection: this.props.singleSelection
? this.props.singleSelection
: ACModal.defaultProps.singleSelection,
.
.
.
I created public static defaultProps, then I put the default values. I passed these attributes to state, then check the values in state. I used the values from state. If you use typescript, you shouldnt forget to write these attributes' names in state interface with their proptypes.