Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

getFieldValue or similar in Formik

Is there a way to get the value of a field inside a click handler in formik?

You can use setFieldValue in there, so I'd assume (but can't find anywhere) that Formik should have something like that for retrieving values:

<Button onClick={() => getFieldValue('name') === 'Test' ? action1 : action2}

What is the correct way to do this in Formik?

like image 955
reectrix Avatar asked May 21 '18 20:05

reectrix


People also ask

How do I get field value in Formik?

Formik uses the name prop to connect the input to values . If it's in an Array, then your index is just another dot-notation path. You use that same name path to access the data.

How do you use handleChange in Formik?

Formik has its own handleChange method that you can use to update the state with user inputs, there is no need to implement your own handleChange method. The handleChange method updates the form values based on the input's name attribute that was changed. The handleChange method is used with input elements.

Is Formik setFieldValue async?

setFieldValue() is async because it uses setState(), but it doesn't receive a callback or return anything. That's why it's hard to get modified values right after that, for example if I want to run submitForm().


2 Answers

Formik passes its values object into your form via props. Imagine you have an input, wired into Formik under the name firstName. You can access the input's value via this.props.values.firstName:

<button onClick={() => console.log(this.props.values.firstName)}>
  Log firstName
</button>

I've test this and verified. It's also demonstrated in several places in the documentation.

like image 167
Reed Dunkle Avatar answered Sep 21 '22 05:09

Reed Dunkle


You can access the current Formik values through onChange

const [currentValues, setCurrentValues] = useState<UserViewModel>();
...

return (
<>
    <Formik
         initialValues={user}
         onChange={({ nextValues }) => { setCurrentValues(nextValues); }}
    >
    ...
    </Formik>
</>

or use a custom React hook

import React from 'react';
import { useField } from 'formik';

const FormSpan = ({ name }) => {
    const [field] = useField(name);
    return (
        <span>{field.value}</span>
    );
};

export default FormSpan;

and inside the Formik

<FormSpan name="preTitle" />
like image 26
Stefan Varga Avatar answered Sep 20 '22 05:09

Stefan Varga