formik change elements on checkbox change

Viewed 14

I am using formik. I have a checkbox that says all day event. if the all day event is selected I want to show a date picker without the time component.

if the all day event is not selected the datepicker has a time component.

this is working properly when the form loads but when I toggle the checkbox the datepicker does not change.

 <Formik enableReinitialize
          validationSchema={validationSchema}
           initialValues={activity}
           onSubmit={values => handleFormSubmit(values)}>

            {({ handleSubmit, isValid, isSubmitting, dirty }) => (
                <Form className='ui form' onSubmit={handleSubmit} autoComplete='off'>
                <MyCheckBox name='allDayEvent' label='All Day Event' />
                {!activity.allDayEvent && 
                <MyDateInput
                        timeIntervals={15}
                        placeholderText='Start Date / Time'
                        name='start'
                        showTimeSelect
                        timeCaption='time'
                        dateFormat='MMMM d, yyyy h:mm aa'
                        title='*Start'  />
                }
               {activity.allDayEvent && 
                <MyDateInput
                        placeholderText='Start Date'
                        name='start'
                        dateFormat='MMMM d, yyyy'
                        title='*Start'  />
                }
         <Button
                disabled ={isSubmitting || !isValid || !dirty}
                 loading={isSubmitting} floated='right' positive type='submit' content='Submit'/>
                <Button as={Link} to='/activities' floated='right'  type='button' content='Cancel'
                />
            </Form>

            )}

          </Formik>
1 Answers

activity is what you're using for the initial values, it's static and does not change (unless you're manually changing it somehow).

Instead, use values.allDayEvent, which is the current state of the field in the Formik state.

{!values.allDayEvent && 
                <MyDateInput
                        timeIntervals={15}
                        placeholderText='Start Date / Time'
                        name='start'
                        showTimeSelect
                        timeCaption='time'
                        dateFormat='MMMM d, yyyy h:mm aa'
                        title='*Start'  />
}
Related