Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Formik react form get value of field on change

I am using Formik for react form with material UI.
I have two fields and I need to do the calculation on that two fields as value change, so I must get the value of those two fields,

    const formik = useFormik({
        initialValues: {
            quantity: '',
            price: '',
            total: '',
        },
        validationSchema: Yup.object({
            quantity: Yup.string().max(5).required('Quantity is required'),
            price: Yup.string().max(5).required('Price is required'),
        }),
        onSubmit: values => {

        },
    })

And here is form

<form onSubmit={formik.handleSubmit}>
    <TextField
        type="number"
        size="small"
        error={Boolean(
            formik.touched.quantity && formik.errors.quantity,
        )}
        helperText={
            formik.touched.quantity && formik.errors.quantity
        }
        label="Quantity"
        margin="normal"
        name="quantity"
        onBlur={formik.handleBlur}
        onChange={formik.handleChange}
        value={formik.values.quantity}
        variant="outlined"
    />
    <TextField
        size="small"
        error={Boolean(formik.touched.price && formik.errors.price)}
        helperText={formik.touched.price && formik.errors.price}
        label="Last Name"
        margin="normal"
        name="price"
        onBlur={formik.handleBlur}
        onChange={formik.handleChange}
        value={formik.values.price}
        variant="outlined"
    />

    {Boolean(
        formik.touched.tax_status && formik.errors.tax_status,
    ) && (
        <FormHelperText error>
            {formik.errors.tax_status}
        </FormHelperText>
    )}
    <Box sx={{ py: 2 }}>
        <Button
            color="primary"
            disabled={formik.isSubmitting}
            fullWidth
            size="large"
            type="submit"
            variant="contained">
            Submit
        </Button>
    </Box>
</form>

How to retrieve values of quantity and price on every change?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

I haven’t use formik so not sure, maybe you can put an useEffect on your formik.values and then do whatever you want with it.

Something like

useEffect(()=>{

    //do your stuff

},[formik.vaues])

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading