vincentsty
vincentsty

Reputation: 3221

Handle formik form outside of formik component

I have a formik form as follow. I am able to submit the form inside formik component. But how could i submit it outside of formik component (inside footer button for this example).

Formik url: Click here

Particulary, how could i access this values handleChange, values, handleSubmit, errors,isValid,touched, handleBlur, isSubmitting, outside of Formik component.

I am doing it in react-native but i guess concept of react would help, particularly with the usage of useRef etc. Found few examples online using ref but none of it work.

<View>
    <Formik
        onSubmit={async values => {
            this.handleSubmit(values);
            await new Promise(resolve => setTimeout(resolve, 1000));
            console.warn(values);
        }}
        validationSchema={validationSchema}>
        {({
        handleChange,
        values,
        handleSubmit,
        errors,
        isValid,
        touched,
        handleBlur,
        isSubmitting,
        }) => (
        <View>
            <Form>
                <Text>First Name</Text>
                <TextInput
                    name="first_name"
                    value={values.first_name}
                    onChangeText={handleChange('first_name')}
                />
                {errors.first_name ? (
                <Text>{errors.first_name}</Text>/>
                ) : (
                    <></>
                )}
                <Button onPress={handleSubmit}>
                    <Text>Submit</Text>
                </Button>
            </Form>
        </View>
        )}
    </Formik>
    <Footer>
        <Button>Submit</Button>
    </Footer>
</View>

Upvotes: 3

Views: 5848

Answers (1)

Shmili Breuer
Shmili Breuer

Reputation: 4147

I had the same issue when creating a reusable popup and having the save button in the popup template and the formik form in the popup content (so I was unable to put the button inside the form since the footer was reused in any popup).

I solved it by adding a ref to the submit button in the form and hiding the button with css and then triggering a click on the hidden submit button pragmatically when clicking on the desired submit button.

Maybe not the cleanest solution but it worked for me.

Here is a basic sample

<Formik>
    ....
    <Field>
    <Field>
    ...
    <button type="submit" style={{display:"none"}}  ref={this.submitButton}/> 
</Formik>

<div className="ftr">
    <button onClick={() => this.submitButton.current.click()}>Save</button>
</div>

Hope this helps

Upvotes: 2

Related Questions