javascriptreactjsformik

how do you use onChange property on react formik radio field


I am looking to use onchange function whenever i click on different radio button. But whenever i try to do this, the default behaviour of formik is lost.

const initialValues = {
hasParent:"no"
}

const handleParentRadioChange = (val) => {
    if (val === 'yes') {
      alert('true');
    } else {
      alert('false');
    }
  };
const submitData = (value) =>{
  console.log(value); 
}


<Formik
   initialValues={initial}
   onSubmit={submitData}
  >
    <Field
    onChange={() => handleParentRadioChange('yes')}
    type="radio"
    name="hasParent"
    value="yes"
    />
    Yes
 <Field
    onChange={() => handleParentRadioChange('no')}
    type="radio"
    name="hasParent"
    value="no"
    />
    No
</Formik> 

How do I perform onChange on formik field without the default formik property being lost?


Solution

  • onChange property does not work in formik radio...you can achieve same thing using through onClick. https://formik.org/docs/examples/radio-group