DEV Community

Discussion on: React Form using Formik, Material-UI and Yup.

Collapse
 
grazianospinelli profile image
Graziano Spinelli

Hi! Giacomo, i don't get how to compose usefield hook with material-ui TextField. Can you write a quick example ?

Thread Thread
 
adamlaurencik profile image
Adam Laurenčík • Edited

Hello, I have created an example of how to use an useField hook with material-ui TextField.

Below is a simple FormikTextField component, that can be reused across the whole application.

import React from 'react';
import { useField } from "formik";
import { TextField, TextFieldProps } from '@material-ui/core';


type FormikTextFieldProps = {
    formikKey: string,
} & TextFieldProps

export const FormikTextField = ({ formikKey, ...props }: FormikTextFieldProps) => {
    const [field, meta, helpers] = useField(formikKey);
    return <TextField
        id={field.name}
        name={field.name}
        helperText={meta.touched ? meta.error : ""}
        error={meta.touched && Boolean(meta.error)}
        value={field.value}
        onChange={field.onChange}
        {...props}
    />
}

It is important that this component is nested under the <Formik> component so it can access the necessary properties inside the useField() hook. You can provide additional styling properties to theFormikTextField component similarly as to the original TextField component.

const ExampleComponent = () => (
    <Formik
        initialValues={{ email: "" }}
        validationSchema={validationSchema}
    >
        <FormikTextField formikKey="email" variant="outlined" />
    </Formik>
)