9

I just trying to create a custom Formik <Field />. It is a <input type = file /> with opacity=0 and depending of values i styling my <Error /> component and <input type = text />. values.photo is ok. The problem is that touched never becoming true, so i can't show my <Error /> component. Can you explain what goes wrong? https://codesandbox.io/s/purple-violet-qgxr3?file=/src/components/FileInput.js

2 Answers 2

16

in your file input component just add this:

form.setTouched({...form.touched,[field.name]: true });

setTouched take object of fields and field.name is the file input name.

5
  • It works not proper, i added one more input to show it. I faced this problem before. When i called setTouched it overwrite all 'touched' object
    – Stas
    Jul 5, 2020 at 11:24
  • if you have multiple input just pass form.touched with the object and assign the field you want check edited aswer.
    – adel
    Jul 5, 2020 at 11:47
  • Ah, can you show some code please? I'm new in Formic
    – Stas
    Jul 5, 2020 at 12:46
  • I've tried to save object form.touched to local state and then to add to this object new property: [field.name]:true and pass it to setTouched. But it seems that in some moment form.touched became undefined and again i overwrite. It is so tricky for me
    – Stas
    Jul 5, 2020 at 12:52
  • what do you mean save form.touched in local state ? you can access it from props .
    – adel
    Jul 5, 2020 at 14:16
-2

when you handle the file input by listening to onChange event. As soon as that onChange method is called you can mark your field asTouched by calling .markAsTouched() so that it would show the error if the condition in validated.

2
  • 2
    Are you sure that .markAsTouched() is a Formik function? I cant find it in the documentation. Sep 1, 2021 at 12:19
  • That's not part of Formik
    – Thremulant
    Feb 27 at 22:13

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.