I'm using formik react library and trying to update one field, based on the onChange
event of another. For example I have one field called email
with onChange={onEmailChange.bind(this, setFieldValue)}
.
This is calling the following function when email is changed:
const onEmailChange = (setFieldValue, e) => {
const domain = e.target.value.replace(/.*@/, '')
setFieldValue('domain', domain, false)
}
The idea here is to update the domain
field with the domain name from the email. But in any case, the issue here is that using setFieldValue
seems to prevent the email
field which is calling the onChange
from updating.
Any suggestions how to handle this?
You will have to use state to make the input field controlled to handle your character replacing issue. In your constructor set initial state as,
this.state={
email:""
}
Change your onChange as,
<input
type="email"
name="email"
onChange={(ev)=>this.setState({email:ev.target.value})}
onBlur={()=>onEmailChange()}
value={this.state.email}
/>
use this.onEmailChange
and this.setFieldValue
if they are member functions
and onEmailChange function as,
const onEmailChange = () => {
const domain = this.state.email.replace(/.*@/, '')
this.setFieldValue('domain', domain, false)
}
Formik now has a good example in their documentation regarding dependent fields
https://formik.org/docs/examples/dependent-fields
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With