sample-usr / react-phone-input

A simple react component to format phone number as the user types
MIT License
88 stars 80 forks source link

Setting placeholder / defaultValue? #28

Open taydotis opened 8 years ago

taydotis commented 8 years ago

What is the ideal way to prefill the form? I cannot get a placeholder to show nor set a default value, regardless of when in the lifecycle I try to add it (actually, I can set the content with this.refs.phoneInput.state.formattedNumber, but only after the user interacts with it). The idea is that the field should be already filled in with the previous form if they are coming back from an earlier save.

MilllerTime commented 7 years ago

@tr0lyat You can use the value prop to set the initial value. It's not documented, but the functionality is clearly there in the source code. Have a look at the component's constructor function.

However, unlike a standard input component, react-phone-input seems to only acknowledge the prop at construction time. Afterwards, changes can only happen by interacting with the field (which sets state.formattedNumber internally). The value of the internal input is indeed controlled by internal state.

While default values are possible via the value prop, the fact that it is only checked at construction time makes the component impossible to use as a controlled component. This seems like the larger issue IMO. I understand that the internal input element is controlled, but it would make a lot more sense if the exported component could be used in a controlled fashion as well. I believe it would be more powerful, and easier to use for those already familiar with React! It would also be a step towards playing well with redux-form.

mohamedtijani commented 7 years ago

The default value does not update with setState

manishksmd commented 7 years ago

how to update default value using set state: I am trying to update phone_work state

<ReactPhoneInput {...phone_work} value={ this.state.phone_work } className="inputMaterial" defaultCountry={'us'} onChange={ (value) => this.setState({phone_work: value})} />

It's not updating value on state change.

ajmas commented 7 years ago

See issue #40. I am providing a fix against that issue, since I had missed this one had been opened.