'formik radio button validation issues
Using formik with a validationSchema, type: 'checkbox' works fine, but type: 'radio' does not. With Yup.boolean().required(), when i check the checkbox, the submit button is successfully enabled, but when I select the radio button, the submit button remains disabled.
Since I need radio button functionality, to simulate it with a checkbox I created an onChange method to disable the checkbox when it's checked, but then the submit button is not enabled when it's checked, just like the issue with using a radio button.
I am using formik 1.5.8, but I upgraded to 2.x to test it, but with the same results.
Based on the formik docs, there is support for radio buttons, but I cannot figured out why it is not working for me
Below is the contrived code I am using, but only use either the radio button or the checkbox, not both at once, but both code examples are included
class Login extends React.Component {
LogInSchema = () => {
const vs = Yup.object().shape({
captcha: Yup.boolean().required(),
});
};
// to simulate a radio button; once it's selected, you can't unselect it
handleChange = event => {
if (event.target.checked) {
event.target.disabled = true;
}
};
renderFocusTrappedForm = () => {
return (
<FocusTrap>
<Form>
<FormRadio name='captcha' />
{/* doesn't enable the submit button when checked */}
<Field
name='captcha'
value='captchaToggle'
type='radio'
checked={this.props.formik.values.captcha}
/>
{/* enables the submit button when checked, but only when no custom onChange is passed */}
<Field
name='captcha'
value='captchaToggle'
type='checkbox'
onChange={this.handleChange} // prevents the submit button from enabling
checked={this.props.formik.values.captcha}
/>
<button>Login</button>
</Form>
</FocusTrap>
);
};
render() {
return (
<Formik
initialValues={this.props.initialValues}
validationSchema={this.LogInSchema}
onSubmit={this.onSubmit}
render={this.renderFocusTrappedForm()}
/>
);
}
}
compose(
connect(mapStateToProps, mapDispatchToProps),
withFormik({
mapPropsToValues: props => ({
captcha: 'captchaToggle',
}),
}),
)(Login);
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
