I want to add an editable prefix to the phone number input. My code looks like this
<input
changeHandler={this.onInputChange}
errors={errors}
onBlur={this.onInputBlur}
onFocus={this.onInputFocus}
resetErrors={clearFieldErrors}
value={` 41${phoneNumber}`}/>
however, after adding the prefix I can't write anything in input. Does anyone know why this is happening and how to fix it?
CodePudding user response:
Instead of changeHandler, you should be using onChange. See examples in https://reactjs.org/docs/forms.html#controlled-components.
Also you might use it as uncontrolled-component and give defaultValue={' 41'} too.
CodePudding user response:
Instead of passing hard coded " 41" in value prop, just initialize the phoneNumber useState
Try the following code, you may find want you looking for.
export default function App() {
const [inputPhoneNumber, setInputPhoneNumber] = React.useState('');
const [phone, setPhone] = React.useState(' 41');
const inputChangeHandler = ({ target }) => {
setPhone(target.value);
};
const submitHandler = (e) => {
e.preventDefault();
setInputPhoneNumber(phone);
setPhone(' 41');
};
return (
<>
<form onSubmit={submitHandler}>
<input onChange={inputChangeHandler} value={phone} />
<button type="submit">Submit</button>
</form>
<h1>{inputPhoneNumber}</h1>
</>
);
}

