How to use custom Input with Formik in React?

前端 未结 5 1254
無奈伤痛
無奈伤痛 2020-12-25 12:18

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 T

相关标签:
5条回答
  • 2020-12-25 12:32

    The accepted answer didn't work for me and didn't show the selected date. It has been almost a year so there might be some changes with the implementation. Though this can be fix by using toDateString() like this

    <DatePicker
       name={'joinedAt'}
       value={values['joinedAt']}
       onChange={e => setFieldValue('joinedAt', e.toDateString())}
     />
    
    0 讨论(0)
  • 2020-12-25 12:46

    https://github.com/jaredpalmer/formik/issues/692

    you need to set value manually if you are using setFieldValue method

    0 讨论(0)
  • 2020-12-25 12:53

    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.

    0 讨论(0)
  • 2020-12-25 12:53

    For html primitive input fields handleChange works like a charm, but for custom components, you've to use setFieldValue to change the value imperatively.

    onChange={e => setFieldValue('joinedAt', e)}
    
    0 讨论(0)
  • 2020-12-25 12:56

    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.

    0 讨论(0)
提交回复
热议问题