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?
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.
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.
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().
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.
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" />
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With