Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React Formik updating one field based on another

Tags:

reactjs

formik

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?

like image 603
dzm Avatar asked Jun 13 '18 02:06

dzm


2 Answers

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)
}
like image 171
Rohith Murali Avatar answered Oct 11 '22 03:10

Rohith Murali


Formik now has a good example in their documentation regarding dependent fields

https://formik.org/docs/examples/dependent-fields

like image 44
Carl Avatar answered Oct 11 '22 04:10

Carl