Blog>
Snippets

Integrating Material-UI TextField with TanStack Form

Illustrate the integration process of Material-UI's TextField component as a form field within TanStack Form.
import { useForm, useField } from '@tanstack/react-form';
import { TextField } from '@mui/material';
Import the necessary hooks from TanStack Form and the TextField component from Material-UI.
function CustomTextField({ field }) {
  const { getInputProps } = useField(field);
  return (
    <TextField
      {...getInputProps({
        id: field.id,
        onChange: e => getInputProps().onChange(e.target.value),
        onBlur: getInputProps().onBlur,
        value: getInputProps().value
      })}
    />
  );
}
Defines a CustomTextField component that utilizes the useField hook from TanStack Form to manage form states and integrates it with Material-UI's TextField component by spreading the getInputProps onto it.
function MyForm() {
  const form = useForm({
    defaultValues: {
      firstName: ''
    },
    onSubmit: async (values) => {
      alert(JSON.stringify(values, null, 2));
    }
  });
  return (
    <form onSubmit={form.handleSubmit}>
      <CustomTextField field='firstName' />
      <button type='submit'>Submit</button>
    </form>
  );
}
Creates a form component that initializes the form using useForm hook with a default value. It utilizes the CustomTextField for form fields and handles the form submission.