DEV Community

Carnegie Hall
Carnegie Hall

Posted on

Formik & Yup simplified:

When learning how to bridge the gap between Backend and Frontend applications it can feel like a lot, especially when it comes to whether you want to use constraints or validations. Luckily React gives you an option to import Formik and Yup. Doing this helps us not only simplify validation handling, but helps with our scalability and maintainability. Both Formik and Yup are libraries, however both vary in features and functionality. Formik's library assists in the creation and management of forms in React applications. Yup on the other hand is a Javascript schema validation that defines validation schemas for our form fields. Yup gives us access to built in validators for several data types, like strings, arrays, and numbers. When we combine these features with a couple of other tools in react we can create a powerful controlled form like the one I created for my Boba Tea Project. Here's the snippet:

`import React, { useState } from 'react'
import { useFormik } from 'formik'
import * as yup from 'yup'
import { headers } from '../globals'
import { useNavigate } from 'react-router-dom'

const TeaItemForm = ({ addTeaItem }) => {
// const [title, setTitle] = useState("")
const [error, setError] = useState({})

const navigate = useNavigate()

const initialValues = {
    name: ""
}

const validationSchema = yup.object({
    name: yup.string().min(3).max(50).required()
})

const handleSubmit = async values => {
    const options = {
        method: "POST",
        headers,
        body: JSON.stringify(values)
    }
    const resp = await fetch("/api/teaItems", options)
    const data = await resp.json()
    if (resp.status !== 201) {
        setError({ data })
    } else {
        addTeaItem(data)
        navigate("/teaItems")
    }
}

const formik = useFormik({
    initialValues,
    validationSchema,
    onSubmit: handleSubmit,
    validateOnChange: false
})

return (
    <div>
        <h3>Create Tea</h3>
        <p style={{ color: 'orange' }}> {formik.errors.error}</p>
        <form onSubmit={formik.handleSubmit}>
            <div>
                <label htmlFor="name">name:</label>
                <input type="text" name="name" id="name" value={formik.values.name} onChange={formik.handleChange} />
                <p style={{ color: 'purple' }}> {formik.errors.name}</p>
            </div> <br />
            <input type="submit" value="Create TeaItem" />
        </form>
    </div>
)
Enter fullscreen mode Exit fullscreen mode

}`

Top comments (0)