DEV Community

Discussion on: React Form using Formik, Material-UI and Yup.

Collapse
 
webarnes profile image
webarnes • Edited

I wrote a small helper to reduce the boilerplate:

const formikProps = (name, initialValue = '') => ({
    name: name,
    value: typeof values[name] !== 'undefined' ? values[name] : initialValue,
    onChange: handleChange,
    onBlur: handleBlur,
    error: touched[name] && errors[name],
    helperText: touched[name] ? errors[name] : ''
});
Enter fullscreen mode Exit fullscreen mode

And then use the spread operator on your components: <TextField {...formikProps('fieldName')}/>

The initial value is required to tell React it's a controlled component. The above function only works for TextFields (Checkboxes, etc, don't directly support helperText so it would need to be modified).

Collapse
 
finallynero profile image
Nero Adaware

Thanks!!!!

Collapse
 
devorein profile image
Safwan Shaheer

I'd like to add a simple enhancement by adding error: touched[name] && Boolean(errors[name]), this will remove an error from the console