I have three same input fields that are masked to have phone format text. All input fields are exactly the same(Phone input field).now I have three states, with three handlePhoneNumber methods. This is not a good practice since all these fields are exactly the same basically.
The UI library I used is Material-UI and i used React-Text-Mask library for my mask component.
What I have so far:
this.state = {
textmask: "( ) - ",
textmask2: "( ) - ",
textmask3: "( ) - ",
}
RenderTextMask(props){
const { inputRef, ...other } = props;
return (
<MaskedInput
{...other}
ref={inputRef}
mask={['(', /[1-9]/, /\d/, /\d/, ')', ' ', /\d/, /\d/, /\d/, '-', /\d/, /\d/, /\d/, /\d/]}
guide={true}
showMask
/>
);
}
My OutlienInput component(from material-UI), looks like this:
<div>
<FormLabel>Phone</FormLabel>
<div>
<OutlinedInput
value={this.state.textmask}
onChange={this.handlePhoneNumber}
inputComponent={this.RenderTextMask}
labelWidth={200}
/>
</div>
</div>
<div>
<FormLabel>Phone</FormLabel>
<div>
<OutlinedInput
value={this.state.textmask2}
onChange={this.handlePhoneNumber2}
inputComponent={this.RenderTextMask}
labelWidth={200}
/>
</div>
</div>
<div>
<FormLabel>Phone</FormLabel>
<div>
<OutlinedInput
value={this.state.textmask3}
onChange={this.handlePhoneNumber3}
inputComponent={this.RenderTextMask}
labelWidth={200}
/>
</div>
</div>
What the problem is: So far I need one state and one handle method for every phone field that I have. As you can see, as the app grows, the code is not really maintainable.
What I want to achieve: I want to have one state and one handle method that handles all three fields(possibly more fields in the future). Or something better than what I currently have. So in the future, if I have to add more fields, i don't have to modify state and add new method every time.
What I have tried so far
I tried to have array testmask as state. The problem is that since I used react-text-mask as my mask library. it only accepts String. If I change "textmask" into array of strings, it will prompts error.