0
votes

I use custom react component with formik which is handled by sending the value where I use it and setting its own state from its parent, so onChange I am always set its react state besides setFieldvalue to set it in formik as I dont use handleChange from formik props.

     <Field
    render={(fields: { field: object; form: formProps }) => {
        return (
            <TextField
            name="title"
            error={errors.title && touched.title}
            value={title}
            onKeyUp={() => null}
            onBlur={handleBlur}
            onChange={(e: { target: { value: string } }) =>
                this.props.onChange('title', e, fields.form)
            }
            placeholder="e.g Introduction to UX Design"
            />
        );
    }}
/>

onChange = (
    stateField: string,
    e: { target: { value: string } },
    form: { setFieldValue: (field: string, value: string) => void }
) => {
// the field is controlled twice here
    form.setFieldValue(stateField, e.target.value);
    this.setState({ [stateField]: e.target.value });
};

it is working correct but it is a hassle for me to handle the two cases in each field and I am not feeling it is the best way to do so, any help ?

1
Is there a special requirment that makes you in-need to control the value twice?Sultan H.
Thank you for the reply, I fixed it with removing the react state and depending directly on state of formik, sorry for not updating the question.Heßaa Ahmad

1 Answers

0
votes

Why do you need to control the value twice? Can you not lift it out of the form state when required, rather than storing in the component state? If you explain the use case more, I think someone will suggest a better way of tackling the problem.