Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use custom Input with Formik in React?

I'm trying to use DatePicker within Formik. But when I click DatePicker's date its form value is not changed. Instead, I got this error:

Uncaught TypeError: e.persist is not a function at Formik._this.handleChange (formik.es6.js:5960)

I shortify code, the code is below

const SomeComponent = () => (     <Formik         render={({             values,             handleSubmit,             handleChange,             setFieldValue         }) => {             return (                 <div>                     <form onSubmit={handleSubmit}>                         <DatePicker                             name={'joinedAt'}                             value={values['joinedAt']}                             onChange={handleChange}                         />                     </form>                 </div>             )         }}     /> ) 

I googled few documents, https://github.com/jaredpalmer/formik/issues/187 and https://github.com/jaredpalmer/formik/issues/86

So I tried like below, but it's not working.

 ...setFieldValue   <DatePicker    name={'joinedAt'}    value={values['joinedAt']}    onChange={setFieldValue}  /> 
like image 277
ton1 Avatar asked Sep 11 '18 08:09

ton1


2 Answers

I resolve this like

<DatePicker    name={'joinedAt'}    value={values['joinedAt']}    onChange={e => setFieldValue('joinedAt', e)} /> 

Update on 2020-03-08:

You can use e.target.value on setFieldValue's second prop, depends on your custom input design. Thanks to Brandon.

like image 82
ton1 Avatar answered Oct 05 '22 23:10

ton1


If you have deeper nesting, you should use Formik Field. Example:

 <Formik     validationSchema={schema}     initialValues={initialValues}     onSubmit={(values, actions) => {}} >    <Field name="colors" component={ColorsEditor}  colors={colorArray}/> </Formik>   const ColorsEditor = ({ field, colors, form, ...props }) => {      return (         <div>             <Button onClick={() => form.setFieldValue('colors', "myValue")}>             </Button>         </div>     ) } 

So the Field component already include the form, where live the setFieldValue that you can use where you need. It also include the errors and needed fields for additional customization.

like image 45
Hugo Gresse Avatar answered Oct 06 '22 00:10

Hugo Gresse